Skip to content

Instantly share code, notes, and snippets.

@iletai
Created March 28, 2021 06:42
Show Gist options
  • Save iletai/125f9848b7494cdb879995c6b2908bc1 to your computer and use it in GitHub Desktop.
Save iletai/125f9848b7494cdb879995c6b2908bc1 to your computer and use it in GitHub Desktop.
Singleton
public class Singleton<T> where T : new()
{
private static T singleton = new T();
public static T instance
{
get
{
return singleton;
}
}
}
public class SingletonMono<T> : MonoBehaviour where T : UnityEngine.Component
{
private void Reset()
{
gameObject.name = typeof(T).ToString();
}
protected static T singleton;
public static T Instance
{
get
{
if (SingletonMono<T>.singleton == null)
{
SingletonMono<T>.singleton = (T)FindObjectOfType(typeof(T));
if (SingletonMono<T>.singleton == null)
{
GameObject go = new GameObject();
go.name = typeof(T).ToString();
SingletonMono<T>.singleton = go.AddComponent<T>();
}
}
return SingletonMono<T>.singleton;
}
}
}
public class SingletonDontDestroy<T> : SingletonMono<T> where T : UnityEngine.Component
{
#region Methods
/// <summary>
/// Use this for initialization.
/// </summary>
protected virtual void Awake()
{
if (singleton == null)
{
singleton = this as T;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment