Changing an Objects Color

Marc Frappier
3 min readMay 22

--

Accessing an objects Components

Every GameObject’’s Components can be accessed in a hierarchical way.

Inspector hierarchy

In the Object’s Inspector, we can find the Transform component where we have access to the object’s position (x,y,z), rotation (x,y,z) and Scale (x,y,z). We can access each individual component.

Acessing an object’s x position

We also have access to the object’s Mesh Renderer where we can find components such a Materials, Lighting, Probes and Additional Settings.

Mesh Renderer

For this exercise, we are interested in the Mesh Renderer > Materials component.

Lets create a new script colorCubeRed and link it to the Cube object in the Hierarchy.

Creating a C# script and linking it to a GameObject

In order to get access to the object’s components, we will first create a variable of type GameObject. Open the script by double clicking on it. Add the following code in the public class:

Creating a variable of type GameObject

When we save the script and then select the Cube object in the Hierarchy, we can see the variable we just created in the script component.

New Script on Cube object

Notice that next to Cube, it says None (Game Object). We need to let Unity know which object we are referring to. To do this, we can drag our Cube object into this slot.

Linking object to variable

Now that Unity knows which object we are referring to, we can access is components.

Lets say we want the cube to turn red when the game starts. In void Start(), we would add the following code in order to access the material inside the Render of the cube.

Accessing Render component of the Cube

This will access the cubes material and set the color to red.

Changing the color upon a condition

Lets say we want the cube to turn green when we hit the left arrow or yellow when we hit the right arrow.

Cube changing colors by pressing Left or Right Arrow keys

After you have setup the object’s movement using transform.Translate,

Moving Object with Keyboard

we check to see what key was pressed and therefore apply the color we want:

Change color by pressing Left or Right arrow keys

Now, when we play the scrips, each time you press the left arrow key, the object will turn green and when you press the right arrow key, the object will turn yellow.

I hope you have enjoyed this brief tutorial on changing the color of an object. See you in the next one.

--

--

Marc Frappier

Poultry Scientist by profession, Computer Scientist at heart. After many years in the poultry business, I have decided to give my passion for technology a shot.