Post tutorial Report RSS Change colors of sprites from code in Unity

Adding temporary effects to sprites using shader variables and manipulating them from script.

Posted by on - Intermediate Textures

One simple way of affecting the appearance of sprites in reaction to in-game actions in via shader parameters that can be accessed via C# scripts on the object.

For example, say one wants to randomly invert the colors of an object, so once a certain amount of time has passed, the object will decide if it inverts or not.

First let's look at the shader that will control this effect:
(I recommend to expand on the Sprites_Default shader included with Unity)


1.
In the Properties section add a parameter, similar to the following:

_INVERSION("INVERTORNOT", Range(0,1)) = 0

This is the parameter that will control wheter the sprite colors are inverted, or not.

2.
Define integer _INVERSION and the v2f struct that will be used in the fragment shader. Do this in the subshader section under PASS and CGPROGRAM.

int _INVERSION;

struct v2f
{
float4 vertex : POSITION ;
half4 color : COLOR;
float2 texcoord : TEXCOORD0;

};

3.
Next, in the subshader portion of the unity shader add a fragment shader that
looks like this:

half4 frag(v2f i) : COLOR
{
fixed4 c = tex2D(_MainTex, i.texcoord)*i.color;

if(_INVERSION == 0)
{
c.rgb = c.rgb* c.a;
}

if(_INVERSION == 1)
{
c.rgb = (1-c.rgb ) * c.a;
}

return c;
}

Now you can try it in the editor. Select the material and you'll see you can change the
value of _INVERSION; if its value is 1, you will get the colors of the sprite inverted

4.
Now, we want to control this effect from a C# script. Don't forget to create a new material
and add this shader to it. Then add this material to the gameobject you want to change colors. Create a new C# script, let's say you name it inversion.cs. Declare variables such as the following:

float timeC;
float timetochange = 5f;
bool invparm;


timeC will be the time counter, so that every timetochange seconds we will decide if we
change the invpar boolean. If invpar is true then we invert the colors, we don't otherwise.
Which is expressed in the function method "invert":

void Invert()
{

int decider = Random.Range(0,50);

if (decider < playerStruct.nlsd + playerStruct.nshroom)
{

if (!invparm)
{
gameObject.GetComponent().material.SetInt("_INVERSION", 0);
}
else
{

gameObject.GetComponent().material.SetInt("_INVERSION", 1);
}
}

}


All that's left is to tell the Update function to call the invert method every timetochange
seconds:


void Update () {

timeC += Time.deltaTime;

if (timeC >= timetochange)
{

Invert();
timeC = 0;
invparm = !invparm;

}

}

You can see the effect here:

2hearts


camion


elephant


postes


Post a comment

Your comment will be anonymous unless you join the community. Or sign in with your social account: