Created
December 15, 2020 09:57
-
-
Save huihut/305aaa2a8e0988d18ff656e65e9d6a93 to your computer and use it in GitHub Desktop.
Unity singleton pattern base class
This file contains 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 SingletonBase<T> where T : new() | |
{ | |
private static T instance; | |
public static T GetInstance() | |
{ | |
if (instance == null) | |
instance = new T(); | |
return instance; | |
} | |
} |
This file contains 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; | |
public class SingletonMonoBase<T> : MonoBehaviour where T : MonoBehaviour | |
{ | |
private static T instance; | |
public static T GetInstance() | |
{ | |
if (instance == null) | |
{ | |
GameObject obj = new GameObject(); | |
DontDestroyOnLoad(obj); | |
obj.name = typeof(T).ToString(); | |
instance = obj.AddComponent<T>(); | |
} | |
return instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment