2020-10-23 Unity 两个特别好用的单例脚本

单例模式在我们开发中使用频率非常的高,这两个脚本省略了我们手写单例的过程,非常好用

基于MonoBehaviour的单例,会创建实体,适合用于有对Unity原生有调用的脚本

using UnityEngine;

/// <summary>
/// 需要创建实体的单例对象,例如声音控制类等
/// </summary>
public class SingletonObject<T>  : MonoBehaviour where T:SingletonObject<T> {

    private static T _instance = null;

    private static readonly object syslock = new object();

    public static T Ins
    {
        get
        {
            if (_instance == null)
            {
                lock (syslock)
                {
                    if (_instance == null)
                    {
                        GameObject obj = new GameObject(typeof(T).Name,typeof(T));
                        _instance = obj.GetComponent<T>();
                         DontDestroyOnLoad(obj);
                        _instance.Spawn();
                    }
                }
            }
            return _instance;
        }
    }

    /// <summary>
    /// 初始化完成
    /// </summary>
    protected  virtual void Spawn()
    {
    }
}

普通单例

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

/// <summary>
/// 单例基类
/// </summary>
public class BaseClass<T> where T : class, new()
{
    private static T _instance;

    private static readonly object syslock = new object();

    public static T Ins
    {
        get
        {
            if (_instance == null)
            {
                //lock关键字用来确保代码块完成运行,避免多线程操作的时候出现问题
                lock (syslock)
                {
                    if (_instance == null)
                    {
                        _instance = new T();
                    }
                }
            }
            return _instance;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。