Changing Color with C# in Unity

David Little
3 min readApr 22, 2021

We can move objects, print results to the console, set up conditions, and a few other functions. Now we are going to change an attribute. In this case, it will be the color.

For this exercise, we want a program that is going to increment a score every time that the space bar is pressed down, and if the score gets to be greater than 50 change the color of an object. We want the object to be red at the start and change to green once the score condition has been met. To start, lets lay this out in pseudo code. Do this in your editor so that you have it to look at while setting up the logic for it.

Next we set up our variables. We only need two of them for this to work, one that describes the object we are going to manipulate and the other to set the score and its initial value.

Next we set the initial color of the cube to red in the Start portion of the script. We do this by digging into the object ‘cube’ the same as you would a transform then position then, say, the x value. In this case we look at the cube, then the rendered, then the material and then that material’s color. Here we get then set that color to red.

We will now use the Update to set some conditions that can be checked while the script is running. We need to watch for the space bar being pressed down, to increment the score. We also need the score itself to be compared to a target value. And, that target value will be used to trigger the color change.

Put then all together and you get this as your final script.

We save this and then go over to Unity to see the results. When I start the game I will scroll the inspector to watch the score change.

This concludes, the beginning, of manipulating objects in Unity using C#. You can see, just by looking around in the inspector, that many of the other attributes can be changed in much the same way. Maybe there will be some examples of this in future posts.

--

--