FindObjectOfType in any scene?

I’m using Singletons to find some of my objects but apparently FindObjectOfType only finds objects in the scene that is currently set as active. What can I do to find a GameObject in ANY scene?

Here’s the Singleton pattern I’m using, it doesn’t work if the singleton is not in the active scene.

using UnityEngine;

// Class to make it easy to create Singletons.

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    protected static T instance;

    /**
       Returns the instance of this singleton.
    */
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = (T)FindObjectOfType(typeof(T));

                if (instance == null)
                {
                    Debug.LogError("An instance of " + typeof(T) +
                                   " is needed in the active scene, but there is none.");
                }
            }

            return instance;
        }
    }

    public static bool Exists()
    {
        return instance != null;
    }
}

You could create a gamebject that contain references by drag and drop in the editor.

1 Like

You could use a game event manager to raise a custom FindObject event. Objects of that type could subscribe to the event in OnEnable, so that they would start listening for the event after being loaded. I suppose they could always just assign themselves to a static list of objects in a singleton class OnEnable as well…