Menu
CoddyTech

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 icon

Challenge

Medium

The rover reports how far away its goal is.

  1. In Start(), set goal = GameObject.Find("Goal").transform;.
  2. In Update(), on Input.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

Practice on your own: Unity playground