Created
December 3, 2014 02:40
-
-
Save zaki/f1561cd7ed036de8e28f to your computer and use it in GitHub Desktop.
Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Friday | |
{ | |
public class Singleton<T> where T : class, new() | |
{ | |
protected static T instance = null; | |
public static T Instance | |
{ | |
get | |
{ | |
if (instance == null) | |
{ | |
instance = new T(); | |
} | |
return instance; | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
namespace Friday | |
{ | |
public class SingletonBehaviour<T> : MonoBehaviour where T : SingletonBehaviour<T> | |
{ | |
protected static T instance = null; | |
protected static bool initialized = false; | |
protected virtual void Setup() {} | |
protected virtual void Initialize() {} | |
public static T Instance | |
{ | |
get | |
{ | |
if (instance == null) | |
{ | |
instance = GameObject.FindObjectOfType(typeof(T)) as T; | |
if (instance == null) | |
{ | |
instance = new GameObject("singleton_" + typeof(T).Name, typeof(T)).GetComponent<T>(); | |
if (instance == null) | |
{ | |
Friday.Logger.LogError(string.Format("Could not create singleton behaviour {0}", typeof(T).Name), category: "SINGLETON"); | |
} | |
else | |
{ | |
instance.Setup(); | |
} | |
} | |
} | |
return instance; | |
} | |
} | |
void Awake() | |
{ | |
if (instance == null) | |
{ | |
instance = this as T; | |
} | |
else if (instance != this) | |
{ | |
Friday.Logger.LogWarning(string.Format("Another instance of {0} already exists", typeof(T).Name), category: "SINGLETON"); | |
DestroyImmediate(this); | |
return; | |
} | |
if (!initialized) | |
{ | |
DontDestroyOnLoad(this.gameObject); | |
initialized = true; | |
instance.Initialize(); | |
} | |
} | |
void OnApplicationQuit() | |
{ | |
instance = null; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment