Menu
CoddyTech

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 icon

Challenge

Medium

Each click moves the signal light on: red, yellow, green, then red again.

  1. Add a Renderer rend; field and set it in Start() with GetComponent<Renderer>().
  2. On Input.GetMouseButtonDown(0), add 1 to an int step field, and set it back to 0 when it reaches 3.
  3. Set rend.material.color to Color.red, Color.yellow or Color.green for 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

Practice on your own: Unity playground