Created
March 28, 2021 06:42
-
-
Save iletai/125f9848b7494cdb879995c6b2908bc1 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
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