Singleton Pattern
Singleton in Unity:
StateManager Singleton
public class StateManager : MonoBehaviour {
public static StateManager instanceRef; //this will be a reference to the only class object instance allowed to exist
//Called before any GameObjects Start() method is called
//Allows pre-initialization: Called once when a script is loaded
void Awake(){
if(instanceRef==null){ //test to see if instanceRef has been assigned to an object yet.
instanceRef=this; //if not, assign it to this current object instance
Debug.Log ("create me");
DontDestroyOnLoad(gameObject); //make sure the gameObject that this is attached to is not destroyed when jumping to a new scene
}
else{ //an instance of this class had previously been created.
Debug.Log ("destroy me");
DestroyImmediate(gameObject); //destroy gameObject and the script object instance, to prevent duplication
}
}
//additional StateManager codeLast updated