Skip to content

Instantly share code, notes, and snippets.

@hungtrinhh
Created October 1, 2023 16:46
Show Gist options
  • Save hungtrinhh/f69702e15d6e3252d8b4080b9c4a18d1 to your computer and use it in GitHub Desktop.
Save hungtrinhh/f69702e15d6e3252d8b4080b9c4a18d1 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : Component
{
private static T instance;
private static bool isGameEnd;
public static T Instance
{
get
{
if (instance == null)
{
var objs = FindObjectsOfType<T>();
if (objs.Length > 0)
{
instance = objs[0];
}
if (objs.Length > 1)
{
Debug.LogWarning($"have {objs.Length} {typeof(T)} in the scene");
}
if (instance == null && !isGameEnd)
{
var gobject = new GameObject(typeof(T).ToString());
instance = gobject.AddComponent<T>();
}
}
return instance;
}
}
private void OnApplicationQuit()
{
instance = null;
isGameEnd = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment