Accessing an objects Components
Every GameObject’’s Components can be accessed in a hierarchical way.
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.
We also have access to the object’s Mesh Renderer where we can find components such a Materials, Lighting, Probes and Additional Settings.
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.
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:
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.
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.
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.
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.
After you have setup the object’s movement using transform.Translate,
we check to see what key was pressed and therefore apply the color we want:
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.