Aimbot-ParallelEnv/Assets/Script/Singleton.cs

40 lines
883 B
C#

using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = (T)FindObjectOfType(typeof(T));
if (_instance == null)
{
Debug.LogError("An instance of " + typeof(T) + " is needed in the scene, but there is none.");
}
}
return _instance;
}
}
protected virtual void Awake()
{
if (_instance == null)
{
_instance = this as T;
}
else
{
Destroy(gameObject);
}
}
// keep this instance through scene change
public void KeepThroughSceneChange()
{
DontDestroyOnLoad(this.gameObject);
}
}