public class UsingSingleton : MonoBehaviour
{
void Start(){
// whatever
}
void Update(){
// to use the singleton, don't forget the .instance !
MySingletonInstance.instance.doStuff();
}
}
public class ControllerManager : Singleton<ControllerManager>
{
void Start(){
// will be called the first time it is instanciated.
// so it behaves like a regular unity object, but will persist
// accross scenes (as long as one instance is present in each scene)
}
public void doStuff(){
// create whatever method you want
}
}
using UnityEngine;
using System.Collections;
public class Singleton<Instance> : MonoBehaviour where Instance : Singleton<Instance> {
public static Instance instance;
public bool isPersistant;
public virtual void Awake() {
if(isPersistant) {
if(!instance) {
instance = this as Instance;
}
else {
DestroyObject(gameObject);
}
DontDestroyOnLoad(gameObject);
}
else {
instance = this as Instance;
}
}
}