Get a Component
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 44 of 85.
A GameObject is a container of components: a Transform, a MeshRenderer that draws it, a collider, your scripts. GetComponent<Renderer>() returns the component of that type on the same object, and through it your script changes what that component does. transform is a ready-made shortcut for the Transform; every other component you fetch yourself.
This cube turns red when Space is pressed. It looks up its Renderer once, in Start(), and keeps it in a field: GetComponent searches the object's components each time it is called, and the answer does not change.
Renderer rend;
void Start()
{
rend = GetComponent<Renderer>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rend.material.color = Color.red;
}
}rend.material gives this object its own copy of its material the first time you use it, so other objects that shared the material keep their color. Unity names some colors for you, such as Color.red, Color.green, Color.blue, Color.yellow and Color.gray; new Color(r, g, b) builds any other, each part from 0 to 1.
Challenge
MediumEach click moves the signal light on: red, yellow, green, then red again.
- Add a
Renderer rend;field and set it inStart()withGetComponent<Renderer>(). - On
Input.GetMouseButtonDown(0), add 1 to anint stepfield, and set it back to 0 when it reaches 3. - Set
rend.material.colortoColor.red,Color.yelloworColor.greenfor step 0, 1 or 2.
Press Play and click the game: the light changes color. Then Check.
Try it yourself
using UnityEngine;
public class SignalLight : MonoBehaviour
{
void Start()
{
}
void Update()
{
// Each click: red, then yellow, then green, then red again
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground