Find by Name
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 42 of 67.
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(), find the object namedGoaland keep its Transform ingoal. - Each time Space is pressed, log the distance from the rover to the goal, as
Distance to goal: 5.
The goal can move, so measure at the moment Space is pressed.
Press Play, click the game and press Space, 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.
}
}
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