Course contentsShow
← Unity Game Development
Lesson 81 of 8282. Scripting and LifecycleFree lesson

Accessing Local Components with GetComponent

Learn to retrieve references to other components attached to the same GameObject to modify their properties and call their public methods.

In this lesson, you will learn how to communicate with other components on the same GameObject by using the GetComponent method to bridge the gap between scripts.

The "Same Room" Concept

Think of your GameObject as a house and your scripts as people living in different rooms. If your "PlayerMovement" script needs to tell the "AudioSource" component to play a sound, it can’t just shout into the void—it needs a reference. Because both components are attached to the same GameObject, they are technically in the same house. GetComponent is the tool that lets you look around the house and retrieve a reference to a specific component so you can interact with it.

How to use GetComponent

To use GetComponent, you call it inside your script and specify the type of component you want within angle brackets < >.

Here is a simple example where we access a Renderer component to change a color:

using UnityEngine;

public class ColorChanger : MonoBehaviour
{
    private Renderer objectRenderer;

    void Start()
    {
        // We reach out and "grab" the Renderer component 
        // attached to this same GameObject
        objectRenderer = GetComponent<Renderer>();

        // Now we can modify the component's properties
        objectRenderer.material.color = Color.red;
    }
}

Why do we store it in a variable?

Notice that we assigned GetComponent<Renderer>() to a variable named objectRenderer. Calling GetComponent is a search process that takes a tiny bit of processing power. By calling it once inside Start() or Awake() and storing the result, we save our game from having to "search the house" again every single frame. Once you have that reference, you have full access to all the public variables and methods of that component, allowing you to trigger animations, change physics settings, or toggle UI elements directly from your own script.

Key Takeaway: Use GetComponent to fetch a reference to another component on your GameObject once during initialization, then store it in a variable so you can efficiently control that component throughout the rest of your script.