Files
beyond/Assets/Scripts/Utils/AutoSingleton.cs
2024-11-20 15:21:28 +01:00

58 lines
1.4 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Beyond
{
public abstract class AutoSingleton<T> : MonoBehaviour where T : AutoSingleton<T>
{
private static T s_instance;
public static T Instance
{
get
{
if (s_instance)
{
return s_instance;
}
else
{
var inst = FindObjectOfType<T>();
if (inst != null)
{
s_instance = inst;
return s_instance;
}
else
{
var go = new GameObject("_" + typeof (T).Name);
go.AddComponent<T>(); // _instance set by Awake() constructor
}
}
return s_instance;
}
}
protected void OnDestroy()
{
if (s_instance == this)
s_instance = null;
}
protected virtual void Awake()
{
if (s_instance == null)
{
s_instance = (T)this;
}
else
{
Debug.LogError("Multiple instances of singleton :"+gameObject.name);
}
}
}
}