Skip to content

Instantly share code, notes, and snippets.

@dyguests
Forked from luke161/Singleton.cs
Last active May 11, 2024 22:04
Show Gist options
  • Save dyguests/494654607d147400471db405ab55df24 to your computer and use it in GitHub Desktop.
Save dyguests/494654607d147400471db405ab55df24 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.
// ReSharper disable once InvalidXmlDocComment
/**
* Singleton.cs
* Author: Luke Holland (http://lukeholland.me/)
*/
using System;
using UnityEngine;
namespace Koyou.Commons
{
public abstract class SingletonMonoBehaviour<T> : MonoBehaviour
where T : MonoBehaviour
{
private static T sInstance;
// ReSharper disable once StaticMemberInGenericType
private static readonly object sInstanceLock = new();
// ReSharper disable once StaticMemberInGenericType
private static bool sQuitting;
public static T Instance
{
get
{
lock (sInstanceLock)
{
if (sInstance != null || sQuitting) return sInstance;
sInstance = FindObjectOfType<T>();
if (sInstance != null) return sInstance;
var go = new GameObject(typeof(T).ToString());
sInstance = go.AddComponent<T>();
DontDestroyOnLoad(sInstance.gameObject);
return sInstance;
}
}
}
protected virtual void Awake()
{
if (sInstance == null) sInstance = gameObject.GetComponent<T>();
else if (sInstance.GetInstanceID() != GetInstanceID())
{
Destroy(gameObject);
throw new Exception($"Instance of {GetType().FullName} already exists, removing {ToString()}");
}
}
protected virtual void OnApplicationQuit()
{
sQuitting = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment