Skip to content

Instantly share code, notes, and snippets.

@inutamago-dogegg
Last active November 30, 2023 19:21
Show Gist options
  • Save inutamago-dogegg/78e11019c927491da1a7f9a05011bf33 to your computer and use it in GitHub Desktop.
Save inutamago-dogegg/78e11019c927491da1a7f9a05011bf33 to your computer and use it in GitHub Desktop.
using System;
using UnityEngine;
public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T> {
[SerializeField] protected bool DontDestroy = false;
private static T _instance;
public static bool HasInstance => _instance != null;
public static T I {
get {
// if singleton already exists, return it
if (_instance) {
return _instance;
}
_instance = FindObjectOfType<T>();
// if found instance, return it
if (_instance) {
return _instance;
}
// if not found instance, create log error
Debug.LogError($"Not found {typeof(T)}");
return null;
}
}
private void Initialize() {
var obj = gameObject;
// if singleton is not this, destroy this instance
if (I != this) {
Debug.LogWarning("Destroy this instance for singleton");
Destroy(obj);
return;
}
if (DontDestroy) {
DontDestroyOnLoad(obj);
}
// rename this gameObject for emphasize singleton
if (obj.name.IndexOf("[Singleton]", StringComparison.Ordinal) < 0) {
obj.name = $"[Singleton] {obj.name}";
}
}
protected virtual void Awake() {
Initialize();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment