Get an 20% OFF using the RELEASE code on your book purchase. For a limited time.

Introduction to the shader programming language

3.3.1. Cg / HLSL variables and connection vectors

This post is also available in…

Continuing with the USB_simple_color shader, notice that within our program there is a variable of sampler2D type and a vector of four dimensions for the definition of the _MainTex texture.

sampler2D _MainTex;
float4 _MainTex_ST;

These connection variables have been declared “global” within the Cg program and correspond to a_MainTex property reference, previously included in the shader Properties

The connection variables are used to connect the values ​​or parameters of the properties with our program variables or internal vectors. In the case of _MainTex, we can assign a texture from the Unity Inspector and use it as a texture in the shader. 

To understand this concept better, let’s assume that we want to create a shader that has the ability to can change colour. To do this, we would have to go to our properties, create a “Color” type and then generate a connection variable within the CGPROGRAM field, in this way we can generate a link between them.

Properties    
{
    // first declare the property
    _Color (“Tint”, Color) = (1, 1, 1, 1)
}
    ...
    CGPROGRAM  
    ...  
    // then declare the connection variable
    sampler2D _MainTex;
    float4 _Color;
    ...
    ENDCG

Generally, the global variables in Cg or HLSL are declared with the word “uniform” (e.g. uniform float4 _Color) however Unity ignores this step since this declaration is included within the shader.

Follow us to stay informed about all the latest news, updates, and more.

Join the group to share your experiences with other developers.

Subscribe to our channel and keep learning game dev!

jettelly-logo

Jettelly Team

We are a team of indie developers with more than 9 years of experience in video games. As an independent studio, we have developed Nom Noms in which we published with Hyperbeard in 2019. We are currently developing The Unity Shader Bible.

Follow us on our social networks.