Unity

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

2020-10-23  本文已影响0人  VECTOR_Y

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

基于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;
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读