Skip to content

Instantly share code, notes, and snippets.

@ertanturan
Created February 9, 2022 15:36
Show Gist options
  • Save ertanturan/432275a9fb6544cec2d3cac478e46f51 to your computer and use it in GitHub Desktop.
Save ertanturan/432275a9fb6544cec2d3cac478e46f51 to your computer and use it in GitHub Desktop.
Unity Scene Singleton Base Class
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