How To Change The Color Of A Sprite Renderer’s Material Through Code

For a lot of video games, you will see visual indicators that help relay information to the player. These can be animations that show a player reeling back from the impact of an enemy's attack, or numbers popping up above an enemy's head when you strike them to display the amount of damage they received. These are all used in order to make a smoother feeling game.

This code allows access to the Sprite Renderer’s Material and lets you change its color.

Make sure the script is attached to the same object as the sprite renderer.

For this example though, I will be showing you how to change your shield’s color in a game to show how much life is left in it. You “COULD” just activate/deactivate 3 different versions of your shield, each with different colors. But a more effective way to do this is by calling the “Sprite Renderer” from a script and changing the colors from there. Let me show you how that’s done.

This script will be placed inside of a script that is attached to the Shield object. Then the two methods, “DamageShield()” and “Restoreshield()” are both called from the player script when the player picks up a shield powerup and when the shield takes damage.

I’ve added 3 different cases for each color state of the shield’s life, 1 case for when the shield is dead, and a “default” case just in case a player manages to get the “_shieldLife” to equal something that’s not listed. You can add as few or as many cases as you’d like.

By serializing the private “Color” variables within the “ColorChanger” script, you allow yourself to custom set the colors of each instance from inside the inspector.

Now when called upon, the material of the object will change according to the specified color.

And there it is in action!

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!