欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

Unity通用泛型单例设计模式(普通型和继承自MonoBehaviour)

时间:2021-04-23 09:30:34|栏目:.NET代码|点击:

单例模式是设计模式中最为常见的,不多解释了。但应该尽量避免使用,一般全局管理类才使用单例。

普通泛型单例:

public abstract class Singleton<T> where T : class, new()
{
  private static T instance = null;

  private static readonly object locker = new object();

  public static T Instance
  {
    get
    {
      lock (locker)
      {
        if (instance == null)
          instance = new T();
        return instance;
      }
    }
  }
}

继承MonoBehaviour的泛型单例:

using UnityEngine;

public abstract class MonoSingleton <T>: MonoBehaviour where T:MonoBehaviour
{
  private static T instance = null;

  private static readonly object locker = new object();

  private static bool bAppQuitting;

  public static T Instance
  {
    get
    {
      if (bAppQuitting)
      {
        instance = null;
        return instance;
      }

      lock (locker)
      {
        if (instance == null)
        {
          instance = FindObjectOfType<T>();
          if (FindObjectsOfType<T>().Length > 1)
          {
            Debug.LogError("不应该存在多个单例!");
            return instance;
          }

          if (instance == null)
          {
            var singleton = new GameObject();
            instance = singleton.AddComponent<T>();
            singleton.name = "(singleton)" + typeof(T);
            singleton.hideFlags = HideFlags.None;
            DontDestroyOnLoad(singleton);
          }
          else
            DontDestroyOnLoad(instance.gameObject);
        }
        instance.hideFlags = HideFlags.None;
        return instance;
      }
    }
  }

  private void Awake()
  {
    bAppQuitting = false;
  }

  private void OnDestroy()
  {
    bAppQuitting = true;
  }
}

使用方法直接用类去继承这两个抽象单例即可,使用T.Instance就可以直接取得该类(T)的唯一实例了。

上一篇:深入理解C# abstract和virtual关键字

栏    目:.NET代码

下一篇:C#控制键盘按键的常用方法

本文标题:Unity通用泛型单例设计模式(普通型和继承自MonoBehaviour)

本文地址:http://www.codeinn.net/misctech/107333.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有