How to reference a Scene GameObject from a prefab?

Hello, I’m having this issue in which I have a prefab player (Red square in prefabs folder) and I want to reference a GameObject (LostMenu) in the scene.

I read that there are some workarounds as Unity doesn’t allow this, such as finding the GameObject through code.
So, in the player’s file I wrote:

private LostMenu lostMenu;

void Start() {
        lostMenu = GameObject.Find("LostMenu").GetComponent<LostMenu>();
        Debug.Log(lostMenu);
}

The problem is the script can’t find the GameObject even though it exists, when I debug the objects, it just throws nullpointerexception (the element is clearly present in the scene as the picture shows). I don’t know if this has something to do with the fact that the prefab is not in the scene.


GameObject.Find doesn't find inactive objects.

So, you have to do other options.
1. Don't use GameObject.Find. Instead, have LostMenu have a static reference to itself. (similar to a singleton, but you might not need it to float around scenes)
2. Have LostMenu script on an active object.
3. Use one of the other find methods that does support inactive objects.
4. Have your script that instantiates the player have a ref to LostMenu that it can pass to your Player object and set up the reference instead of trying to in Start on the Player.
5. Probably other ways as well..

2 Likes

Your "LostMenu" game object is inactive in the scene, and the default behavior of Find is to ignore inactives.

It is far better and easier to use FindObjectOfType instead of Find

//the boolean is to indicate whether to include inactives in the search or not
lostMenu = GameObject.FindObjectOfType<LostMenu>(true);
2 Likes

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

More information: Regarding GameObject.Find · UnityTipsRedux

More information: Why cant i find the other objects?

2 Likes

Thank you very much!
I used

lostMenu = Resources.FindObjectsOfTypeAll<LostMenu>()[0]

as I only have one LostMenu instance and it instantly worked!

The more common solution is to assign the reference when spawning the prefab:

Menu menu1=Intantiate(menuPrefab);
menu1.lostObject=[my inspector-assigned menu-link]