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
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.
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground