Skip to content

Instantly share code, notes, and snippets.

@eslof
Forked from ErikOG/SingletonMonoBehaviour.cs
Created June 6, 2021 18:10
Show Gist options
  • Save eslof/ac961773ee7e5b6bf027fce65b7802a4 to your computer and use it in GitHub Desktop.
Save eslof/ac961773ee7e5b6bf027fce65b7802a4 to your computer and use it in GitHub Desktop.
Most singletons out there will 'destroy' other instances, I think there shouldn't be more than one instance of it to begin with, if there are we just want to find out about it so we can fix the core of the problem and not just the symptom.
using UnityEngine;
#if UNITY_EDITOR || DEBUG
using System;
using UnityEngine.SceneManagement;
#endif
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour {
private static T _instance = null;
public static T Instance {
get {
if (_instance == null) {
#if UNITY_EDITOR || DEBUG
_instance = findInstance();
#else
_instance = (T)FindObjectOfType(typeof(T));
#endif
}
return _instance;
}
}
#if UNITY_EDITOR || DEBUG
const string SINGLETON_DUPE_ERROR = "Multiple instances ({0}) of: {1} in scene {2}.";
const string SINGLETON_NOT_IN_SCENE_ERROR = "Attempting to access .Instance of singleton: {0} while it is not in scene ({1}).";
private static T findInstance() {
Type _type = typeof(T);
T[] _instances = (T[])FindObjectsOfType(_type);
int _count = _instances.Length;
if (_count > 1) {
Debug.LogErrorFormat(
SINGLETON_DUPE_ERROR,
_count, _type.ToString(), SceneManager.GetActiveScene().name);
} else if (_count == 0) {
Debug.LogErrorFormat(SINGLETON_NOT_IN_SCENE_ERROR,
_type.ToString(), SceneManager.GetActiveScene().name);
return null;
}
return _instances[0];
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment