Skip to content

Instantly share code, notes, and snippets.

@123tris
Last active October 22, 2024 02:00
Show Gist options
  • Save 123tris/f0964841c92a66412a9399c81c86731b to your computer and use it in GitHub Desktop.
Save 123tris/f0964841c92a66412a9399c81c86731b to your computer and use it in GitHub Desktop.
Singleton for Unity. Could possibly be improved on.
using UnityEngine;
using UnityEngine.Assertions;
public class Singleton<T> : BaseBehaviour where T : MonoBehaviour
{
public static T Instance => GetInstance();
/// <summary>GetInstance gets called by the getter Instance, however GetInstance can be used to get extra control such as turning off exceptions and allowing null or generate the instance when it can't be found </summary>
public static T GetInstance(bool throwException = true, bool generateInstance = false)
{
if (instance == null)
{
T[] foundInstances = FindObjectsOfType<T>(true);
if (foundInstances.Length == 0)
{
if (generateInstance)
{
GameObject gameObject = new GameObject($"{typeof(T).Name} Manager");
instance = gameObject.AddComponent<T>();
}
}
else
{
if (foundInstances.Length > 1)
Debug.LogError($"You have multiple instances of a Singleton of type {typeof(T).Name}");
instance = foundInstances[0];
}
if (throwException)
Assert.IsTrue(instance, $"The component {typeof(T).FullName}, could not be found in the scene");
}
return instance;
}
private static T instance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment