Find by Name
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 56 of 85.
GameObject.Find("Player") searches the scene for an active object with exactly that name and returns it, or null when there is none. It saves wiring a field in the Inspector, at a cost: it looks through every object in the scene. So call it once, in Start(), and keep the result in a field. This security camera finds the Player when the game starts and watches it on every frame:
private Transform player;
void Start()
{
player = GameObject.Find("Player").transform;
}
void Update()
{
transform.LookAt(player);
}The name must match exactly, capitals and spaces included: "player" or "Player " finds nothing. Find also skips inactive (hidden) objects. A failed search returns null quietly, and the error shows up on the next line that uses the result: here, .transform throws NullReferenceException. A path such as "Car/Wheel" finds the Wheel that is a child of Car.
Challenge
MediumThe rover reports how far away its goal is.
- In
Start(), setgoal = GameObject.Find("Goal").transform;. - In
Update(), onInput.GetKeyDown(KeyCode.Space), log"Distance to goal: " + Vector3.Distance(transform.position, goal.position).
Press Play and press Space: the Console shows Distance to goal: 5. Then Check.
Try it yourself
using UnityEngine;
public class Beacon : MonoBehaviour
{
private Transform goal;
void Start()
{
// Find the object named Goal and keep its Transform in goal.
}
void Update()
{
// Space: log the distance to the goal.
}
}
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