I was wondering if there was a way to run a Manager / Singleton class when my game starts without attaching it to any gameObject. I need this class to hold references to my current camera and other such objects which I'd like to access from a variety of different scenarios.
This is possible since Unity 5 or so, using [RuntimeInitializeOnLoadMethod]
See: Unity - Scripting API: RuntimeInitializeOnLoadMethodAttribute
You need at least one script attached to a gameobject somwhere in your scene.
However you can use that script's Start() function as a hook from which to instantiate any number of your own classes which themselves aren't attached to a GameObject.
If you're going to create new instances like this, make sure that they don't inherit from MonoBehaviour, since the way that MonoBehaviour works makes some assumptions that it is attached to a GameObject.
So the rule for creating instances of scripts at runtime are:
-
For MonoBehaviours, always use:
gameObject.AddComponent(MyScript)
-
For non-MonoBehaviours, always use:
new MyScript();
In summary, you can have scripts running which aren't attached to GameObjects, but you can't get scripts running in the first place without at least one attached to a GameObject, to "kick things off".
IN addition you can have a singleton class that is not a monobehavior, that has links to game object in your scene. You can Call : AppState.Instance().goGame=this.gameObject;
and can be called from within empty game object script.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AppState {
public static AppState _instance = null;
//holder for reference
;
public GameObject goGame;
public AppState() {
Debug.Log("constructor ");
}
/* singleton */
public static AppState Instance() {
if (_instance==null)
{
_instance=new AppState() ;
}
return _instance;
}
}
Make your class extend UnityEngine.ScriptableObject, then use the ScriptableObject.Awake() function to do what you want
Best Solution : Unity - Manual: Running Editor Script Code on Launch