Menu
CoddyTech

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 icon

Challenge

Medium

The 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
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics