Day 6: Changing colors in Unity

Jake Boere
3 min readMay 16, 2021

--

This time as the title suggests we’re going to be changing the color of an object using code. To start we need the object so we need to create a new 3D object in the hierarchy. Next create you script and open it so you can start writing your pseudo code, for this example we want to change the color when we reach a certain score and start the object as a different color. Now we need to create our variables which we need one for our game object and one for our score. Next we need to write in void start the code to set the color to red when we start the game. To do this we need to get the game object using the variable we made for it, then get the component that has the color which is the renderer, then we need to initialize the renderer and access the material then lastly the color. Once we’ve gotten to the color we want to change the color and make it equal to the color red. If you’ve followed along you should end up with something like this:

Now we need to change the color when we reach a specific score but first we need to actually increase the score which we will do in an if statement and make it so when we press the space bar down we increase the score by 20. So write you if statement with the condition of when the space bar is pressed the score is equal to the score plus 20. Then we need to write another if statement for the color change which means we write for the condition when the score is equal to or greater than 50 then write the color change code again except make it a different color to change to for this example I will be changing it to green. When it’s all written your code should look something like this:

After your script is all written you will need to drag your 3D object to the game object variable you made so that the script knows which game object to make those changes to. To do that go to your inspector where the script you made is attached to and there should be a box looking for a game object, just drag the game object there and it should all be setup. If it works properly you should end up with something like the video at the top.

--

--

Jake Boere
Jake Boere

Written by Jake Boere

I am hard working Game development student learning as much about game development and unity as possible.

No responses yet