Menu
CoddyTech

References Beat Find

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 59 of 85.

A script can reach another object four ways: a field set in the Inspector, GameObject.Find by name, a tag search, or FindAnyObjectByType by type. For an object that is in the scene from the start, Unity code uses the Inspector field, for three reasons:

  • Speed. The reference is filled in before the game starts. Every search goes through the scene's objects, and a search in Update() does that on every frame.
  • Safety. A name in a string breaks when someone renames the object: Find returns null and the error appears later, on whatever line uses it. An empty Inspector field fails with UnassignedReferenceException, which names the field and the script.
  • Clarity. The Inspector shows what a script depends on. A Find call hides it inside the code.
// set once in the Inspector: no search, and a rename changes nothing
[SerializeField] private Transform door;

// searched on every frame, and null after the door is renamed
void Update()
{
    Transform d = GameObject.Find("Door").transform;
}

Searches have their place: objects that only exist once the game runs, such as one spawned while playing, and scripts that must work in any scene. Even then, search once in Start() and keep the result in a field.

Try it yourself

This lesson doesn't include a code challenge.

All lessons in Unity Scripting Basics

Practice on your own: Unity playground