Change a Sprite’s Transparency

January 20, 2015 - Scripting

Adjusting a sprite’s transparency can add dynamic ‘juice’ to your game. You can make items flash on and off, make translucent ghost, or fade away your UI buttons. It happens to be really easy to achieve via Unity’s SpriteRenderer component.

Here’s a quick example from my game Game of Clowns (Windows Phone, Windows Store, and Android):


That finger is a hint from the first level showing the player where to tap to continue the game. It fades in and out by cycling the alpha channel of the sprite.

Change a Sprite’s Transparency

You can’t change the alpha value directly, so instead you need to create a Color variable and fill it with the sprite’s colour information. Then modify the copy and then copy the copy into the sprite’s color property.

// store a reference to the SpriteRenderer on the current GameObject
SpriteRenderer spRend = obj.transform.GetComponent<SpriteRenderer>();
// copy the SpriteRenderer's color property
Color col = spRend.color;
//  change col's alpha value (0 = invisible, 1 = fully opaque)
col.a = 0.5f; // 0.5f = half transparent
// change the SpriteRenderer's color property to match the copy with the altered alpha value
spRend.color = col;

It’s that simple – modify the alpha value to be as transparent as you need it. I bet you can think of lots of ways to use this to give your Unity game more pizazz!

Leave a Reply

Your email address will not be published.