Created
February 9, 2022 15:36
-
-
Save ertanturan/432275a9fb6544cec2d3cac478e46f51 to your computer and use it in GitHub Desktop.
Unity Scene Singleton 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
using UnityEngine; | |
public class Singleton<T> : MonoBehaviour where T : Component | |
{ | |
[Header("Singletion Properties")] | |
public bool DontDestroyOnLoading = false; | |
public static T Instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
{ | |
_instance = FindObjectOfType<T>(); | |
if (_instance == null) | |
{ | |
GameObject obj = new GameObject(typeof(T).Name); | |
obj.AddComponent<T>(); | |
} | |
} | |
return _instance; | |
} | |
} | |
private static T _instance; | |
protected virtual void Awake() | |
{ | |
if (Instance == null) | |
{ | |
_instance = this as T; | |
if (DontDestroyOnLoading) | |
DontDestroyOnLoad(gameObject); | |
} | |
else | |
{ | |
if (Instance.GetInstanceID() != this.GetInstanceID()) | |
{ | |
Destroy(gameObject); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment