单例脚本(3种方式)

第一种:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 不需要挂载就能使用
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseManager<T> where T :new ()
{
    private static T _instance;
    public static T GetInstance()
    {
        if (_instance ==null)
        {
            _instance = new T();
        }
        return _instance;
    }

}

第二种:

using UnityEngine;
//可挂载

public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<T>();
                if (_instance == null)
                {
                    _instance = new GameObject(typeof(T).ToString()).AddComponent<T>();
                }
            }
            return _instance;
        }
    }
}

第三种:

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

public class ToolSingleCase<T> : MonoBehaviour where T :MonoBehaviour
{
    private static T my_instance = null;
    public static T instance_
    {
        get
        {
            if (my_instance ==null)
            {
                my_instance = FindObjectOfType<T>();
                if (my_instance ==null)
                {
                    GameObject go = new GameObject(typeof(T).Name);
                    my_instance = go.AddComponent<T>();
                    DontDestroyOnLoad(my_instance);
                }
                return my_instance;
            }
            return my_instance;
        }
    }
}

 

posted @ 2025-07-07 17:26  剑起苍穹  阅读(11)  评论(0)    收藏  举报
/*鼠标点击特效*/