Unity C# singleton mode, generic singleton mode, Mono singleton mode, Mono automatic singleton mode

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

public class Singleton<T> : MonoBehaviour where T : Singleton<T> 
{
    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 IsInitialized 
    {
        get { return instance != null; }
    }

    protected virtual void OnDestroy() 
    {
        if (instance == this) 
        {
            instance=null;
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SingletonAutoMono<T> : MonoBehaviour where T :MonoBehaviour
{
    private static T instance;
    public static T GetInstance()
    {
        if (instance == null) 
        {
            GameObject obj = new GameObject();
            obj.name = typeof(T).ToString();
            //让这个单例对象 过场景 不移出
            DontDestroyOnLoad(obj);
            instance = obj.AddComponent<T>();
        }
        return instance;
    }

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

public class SingletonMono<T> : MonoBehaviour where T:MonoBehaviour
{
    private static T instance;
    public static T GetInstance() 
    {
        return instance;
    }

    protected virtual void Awake()
    {
        instance = this as T;
    }
}

Guess you like

Origin blog.csdn.net/weixin_46711336/article/details/128670207