Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 ยท C# Scripting

Finding and Referencing Components

Learn how Unity scripts talk to each other: GetComponent, TryGetComponent, children and parents, Find, FindFirstObjectByType, Inspector references, null checks and events.

A game is a conversation between objects: the player hits an enemy, the enemy tells the score manager, the score manager updates the UI. To talk, scripts first need a reference to each other. Unity offers many ways to get one, from dragging in the Inspector to searching the scene, and they differ greatly in speed and safety. This lesson ranks them and shows when to use each.

The Unity scripts are read-only here. The stand-ins use plain C# to model null references and event-based communication.

Option 1: drag a reference in the Inspector

The best default. Declare a [SerializeField] field and assign it in the editor:

C#
using UnityEngine;

public class Door : MonoBehaviour
{
    [SerializeField] Light warningLight;       // drag the light here
    [SerializeField] Animator animator;        // or any component type

    public void Open()
    {
        warningLight.color = Color.green;
        animator.SetTrigger("Open");
    }
}

It costs nothing at run time, survives renames, and is visible in the editor. The limit: it only works inside a scene or prefab, not for objects that are created at run time (but you can pass the reference in code when you instantiate them).

Option 2: GetComponent on the same object

When a script needs a sibling component, call GetComponent<T>() once, in Awake, and store it:

C#
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Jumper : MonoBehaviour
{
    Rigidbody rb;

    void Awake()
    {
        rb = GetComponent<Rigidbody>();    // cache it
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
            rb.AddForce(Vector3.up * 6f, ForceMode.Impulse);
    }
}

Calling GetComponent every frame is a classic performance mistake. It is not horribly slow, but it adds up across hundreds of objects. Cache it.

TryGetComponent: the safe version

GetComponent returns null when the component is missing, and using that result throws NullReferenceException. TryGetComponent returns a bool and does not allocate an error object in the editor:

C#
if (other.TryGetComponent<Health>(out var health))
{
    health.TakeDamage(10);        // only runs if the other object has Health
}

This is the idiomatic pattern when you hit something unknown (a bullet touching any object) and want to do something only if it has a certain component.

Option 3: children and parents

C#
// read-only Unity script
var renderers = GetComponentsInChildren<Renderer>();       // this object and all descendants
var childLight = GetComponentInChildren<Light>(true);      // true: include inactive objects
var parentBody = GetComponentInParent<Rigidbody>();        // search up the hierarchy

Transform hand = transform.Find("Arm/Hand");               // by path, direct child path
Transform first = transform.GetChild(0);
foreach (Transform child in transform) { /* each direct child */ }

Notice that GetComponentInChildren also includes the object itself first. A typical use is finding a collider or renderer on a child mesh of the object that holds your script.

Option 4: searching the whole scene

These work but cost time, so call them once (in Start) and never in Update:

C#
// read-only Unity script
GameObject player = GameObject.FindWithTag("Player");                  // by tag, fast-ish
Player p = Object.FindFirstObjectByType<Player>();                     // by type, first match
Enemy[] enemies = Object.FindObjectsByType<Enemy>(FindObjectsSortMode.None); // all of a type
GameObject byName = GameObject.Find("Main Camera");                    // by name: slowest, fragile

Notes:

  • FindObjectOfType and FindObjectsOfType are the older names; current Unity versions mark them obsolete in favor of FindFirstObjectByType and FindObjectsByType (pass FindObjectsSortMode.None for speed).
  • GameObject.Find fails silently (returns null) if the name changes, and cannot find inactive objects.
  • Tag lookups need a defined tag, and FindWithTag returns just one object.

Option 5: static access (singletons) and events

For things there is exactly one of (a game manager, an audio manager) a singleton gives easy access:

C#
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }
    public int score;

    void Awake()
    {
        if (Instance != null && Instance != this) { Destroy(gameObject); return; }
        Instance = this;
        DontDestroyOnLoad(gameObject);
    }
}

// anywhere else:
GameManager.Instance.score += 10;

Singletons are convenient but create hidden dependencies; use sparingly. A cleaner way to decouple objects is events. The coin does not need to know the score display; it just announces "I was collected". Anyone who cares subscribes. See the event example in Lifecycle Methods.

Null references: the most common error

NullReferenceException: Object reference not set to an instance of an object means you used a reference that points at nothing. The Console tells you the script and line. Typical causes:

  1. An Inspector field left empty (None).
  2. GetComponent returned null because the component is missing.
  3. Find did not find the object (misspelled, inactive).
  4. The referenced object was destroyed.

Unity overrides == on its objects: a destroyed object compares equal to null, even though the C# reference is still non-null. Because of that, avoid ?. and ?? with Unity objects; they bypass Unity's check. Use if (target != null) instead.

Modeling null checks and TryGet in plain C#

This stand-in shows the safe patterns. A lookup returns null for a missing component; TryGet avoids the crash by returning a bool.

C# GetComponent vs TryGetComponent (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A bullet can hit anything, so TryGetComponent is exactly right: act only if the object can be damaged.

Decoupling with events: a stand-in

Instead of Coin holding a reference to the score display, it raises an event. The display subscribes. Adding another listener (an audio player, an achievement tracker) needs no change to Coin.

C# Events instead of direct references (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Performance ranking and a rule of thumb

Method Cost Use it
Inspector reference none at run time Always when possible
Cached GetComponent tiny, once In Awake
GetComponent per frame small but wasteful Avoid
FindFirstObjectByType, FindWithTag scans the scene Once in Start
GameObject.Find by name scans, string compare Avoid

Rule of thumb: Inspector reference first, then GetComponent in Awake, then TryGetComponent for unknown objects, then events or a manager for cross-object messages. Searching the scene is the last resort.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should you normally call GetComponent and store the result?

    Caching in Awake avoids repeated lookups.
  2. 2. What does TryGetComponent do?

    It is the safe version of GetComponent for objects that may not have the component.
  3. 3. What does NullReferenceException typically mean in Unity?

    A field was never assigned, or a lookup returned null, or the object was destroyed.
  4. 4. Which is the cleanest way to let many unrelated objects react to a coin pickup?

    Events decouple sender and listeners.

Summary

  • Prefer Inspector references; cache GetComponent in Awake; use TryGetComponent for unknown objects.
  • GetComponentInChildren and GetComponentInParent search the hierarchy.
  • Scene searches (FindFirstObjectByType, FindWithTag, Find) are slow; do them once, not per frame.
  • Singletons offer easy access but hidden coupling; events decouple objects.
  • Check Unity objects with != null; avoid ?. on them.

Next: Instantiate, Destroy and Coroutines