Course contentsShow
← Unity Game Development
Lesson 84 of 8282. Scripting and LifecycleFree lesson

Locating Objects Using Name Searches

Master the use of GameObject.Find to retrieve specific objects by their unique names while learning the performance risks associated with this approach.

In this lesson, you will learn how to locate specific GameObjects in your scene by referencing them directly via their unique names using GameObject.Find.

Why Use Name Searches?

Sometimes, you need your script to interact with a specific object—like a "Player" or a "ScoreManager"—that isn't linked to your script in the Inspector. While you have previously learned to find objects using Tags, sometimes a direct name lookup is the most straightforward way to establish a reference, especially when you are prototyping or setting up unique, singular objects in a scene.

How to use GameObject.Find

You can locate an object by passing its exact name as a string to the GameObject.Find() method. Here is how it looks in practice:

void Start()
{
    // Searching the scene hierarchy for an object named "Player"
    GameObject player = GameObject.Find("Player");

    if (player != null)
    {
        Debug.Log("Found the player: " + player.name);
    }
    else
    {
        Debug.LogWarning("Could not find an object named Player!");
    }
}

The Performance Cost

While GameObject.Find is easy to write, it comes with a significant performance warning. When you call this method, Unity must iterate through every single active GameObject in your scene hierarchy to check if its name matches your search string.

If you place this call inside your Update method (which runs every single frame), you are forcing Unity to perform a costly search dozens or hundreds of times per second. This will quickly create performance bottlenecks, which you might remember seeing in the Profiler during your earlier performance analysis lessons.

Best Practices

To keep your game running smoothly:

  1. Cache the result: If you need the object, find it once inside Start or Awake and store it in a private variable. Never search for it every frame.
  2. Be specific: Ensure your names are unique. If you have two objects named "Enemy," GameObject.Find will only return the first one it encounters, which might not be the one you intend to use.

Key Takeaway: Use GameObject.Find only during initialization to locate unique objects, and always store the result in a variable to avoid expensive repeated searches.