Skip to content

Instantly share code, notes, and snippets.

@zaki
Created December 3, 2014 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaki/f1561cd7ed036de8e28f to your computer and use it in GitHub Desktop.
Save zaki/f1561cd7ed036de8e28f to your computer and use it in GitHub Desktop.
Singleton
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;
}
}
}
}
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