Unity 泛型单例

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Singleton : MonoBehaviour where T : Singleton
{
    private static T instance;
    public static T Instance
    {
        get { return instance; }
    }

    protected virtual void Awake()
    {
        if (instance != null)
            Destroy(gameObject);
        else
            instance = (T)this;
    }
    public static bool IsInitalized
    {
        get { return instance != null; }
    }
    protected virtual void OnDestroy()
    {
        if(instance == this)
        {
            instance = null;
        }
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : Singleton
{
    protected override void Awake()
    {
        base.Awake();
        DontDestroyOnLoad(this);
        PieceControler.OnInit();

    }
}
using UnityEngine;

public class PieceControler : SingletonBase
{
    public string str = "";
    static public void OnInit()
    {
        Debug.Log("PieceControler OnInit");
    }
}

你可能感兴趣的:(Unity2019.4,unity)