References Beat Find
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 45 of 67.
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
nulland 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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon