Last active
June 20, 2024 15:20
-
-
Save luke161/5ec0d91f4bf2366dfafb3014c6bd9466 to your computer and use it in GitHub Desktop.
Unity MonoBehaviour Singleton. Base class for creating a singleton in Unity, handles searching for an existing instance, useful if you've created the instance inside a scene. Also handles cleaning up of multiple singleton instances in Awake.
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
/** | |
* Singleton.cs | |
* Author: Luke Holland (http://lukeholland.me/) | |
*/ | |
using UnityEngine; | |
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour | |
{ | |
private static T _instance; | |
private static readonly object _instanceLock = new object(); | |
private static bool _quitting = false; | |
public static T instance { | |
get { | |
lock(_instanceLock){ | |
if(_instance==null && !_quitting){ | |
_instance = GameObject.FindObjectOfType<T>(); | |
if(_instance==null){ | |
GameObject go = new GameObject(typeof(T).ToString()); | |
_instance = go.AddComponent<T>(); | |
DontDestroyOnLoad(_instance.gameObject); | |
} | |
} | |
return _instance; | |
} | |
} | |
} | |
protected virtual void Awake() | |
{ | |
if(_instance==null) _instance = gameObject.GetComponent<T>(); | |
else if(_instance.GetInstanceID()!=GetInstanceID()){ | |
Destroy(gameObject); | |
throw new System.Exception(string.Format("Instance of {0} already exists, removing {1}",GetType().FullName,ToString())); | |
} | |
} | |
protected virtual void OnApplicationQuit() | |
{ | |
_quitting = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perfect!
I used it to replace the old solution I had been using for several years