Can't find gameobjects by name?

I have 13 gameObjects in my scene, which are named like this:

  • colored1
  • colored2
  • colored13

When I run this script, all instances of the GameObject.Find() invocations return null:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MainScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        for(int i = 1; i <= 13; i++)
        {
            string scope = "colored" + i;
            Debug.Log("Searching for " + scope);
            GameObject tile = GameObject.Find(scope);
            if(tile == null)
            {
                Debug.Log(scope + " has been found");
            }
            else
            {
                Debug.Log(scope + " could not be found");
            }
        }
    }
}

However when I run THIS script, all gameobjects are found correctly (after I tagged them with “Tile”):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MainScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        GameObject[] tiles = GameObject.FindGameObjectsWithTag("Tile");

        foreach(GameObject gameObject in tiles)
        {
            Debug.Log(gameObject.name);
        }
    }
}

When I run that second script, all of the names of the gameObjects are also printed in the console correctly, colored1, colored2 and so on… why does the GameObject.Find() function not return any of them when I apparantly search for the correct names?

Your if statement is checking if the tile is Equal to null. If it is, then the debug.log will say the object is found. Else it will say Object is not found. Swap the == for a != in the if statement.


Here’s my solution. This version checks if the object is equal to something rather than null. If null then the object is not found. If equal to something then the object is found.

// Start is called before the first frame update
    void Start()
    {
        for (int i = 1; i <= 13; i++)
        {
            string scope = "colored" + i;
            Debug.Log("Searching for " + scope);

            GameObject tile = GameObject.Find(scope);

            if (tile != null)
            {
                Debug.Log(scope + " has been found");
            }
            else
            {
                Debug.Log(scope + " could not be found");
            }
        }
    }