Prefab Scripts: Singletons vs GameObject.Find()

In Hugo’s (CodeMonkey’s) Unity course, he often will use a Singleton to work with globally available classes outside a prefab. I understand the purpose of the Singleton pattern, the communication of design intent, etc, but I am confused about the notion that “global objects outside a prefab are not available to a prefab”. Singletons and GameObject.Find() both seem to work to access global objects in the scene. Maybe this means that you can’t place global objects into a prefab at the inspector level? Is another way of saying this that “global objects must be accessed by prefab code programmatically (instead of at the inspector level)”?

Interesting, I didn’t realize that you could make Singletons persist across scenes by putting something like

void Awake() {
    DontDestroyOnLoad(gameObject);
}

in the Singleton. That makes much more sense why it would be a good pattern with prefabs.

You can’t link a scene object to a prefab in the inspector. This means, as you’ve surmised, that you have to link scene objects programatically. The Singleton pattern just serves to make things a bit easier (and quicker) than a GameObject.FindObjectOfType() call.

Yes, but there’s a catch… if each scene contains that Singleton (which is a common practice), then you need to add just a bit more code.

void Awake()
{
    if(Instance==null)
    {
         Instance=this;
         DontDestroyOnLoad(gameObject); 
    }
    else
    {
         Destroy(gameObject);
    }
}
1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms