Get a Component
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 30 of 67.
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
MediumThe signal light starts red. Each click moves it on to its next color, in this order: red, yellow, green, then red again, and so on.
Get the Renderer once, in Start(), and keep it in a field. Use Color.red, Color.yellow and Color.green.
Press Play, click the game a few times, 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
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon6GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch