Singleton.cs 1.35 KB
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;

    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<T>();

                if (_instance == null)
                {
                    GameObject singleton = new GameObject();
                    _instance = singleton.AddComponent<T>();
                    singleton.name = $"Singleton_{typeof(T)}";
                    DontDestroyOnLoad(singleton);
                }
            }

            return _instance;
        }
    }

    /// <summary>
    /// 初始化单例
    /// </summary>
    protected virtual void Awake()
    {
        if (_instance == null)
        {
            _instance = this as T;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            if (this != _instance)
            {
                Debug.LogWarning($"[Singleton] 发现重复的单例实例 '{gameObject.name}',正在销毁");
                Destroy(gameObject);
            }
        }
    }

    /// <summary>
    /// 销毁
    /// </summary>
    protected virtual void OnDestroy()
    {
        if (this == _instance)
        {
            _instance = null;
        }
    }
}