博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c#及unity单例模板
阅读量:4538 次
发布时间:2019-06-08

本文共 2411 字,大约阅读时间需要 8 分钟。

c#:使用泛型实现单例

using System; using System.Collections.Generic; using System.Text; using System.Reflection; ///  /// 1.泛型 /// 2.反射 /// 3.抽象类 /// 4.命名空间 ///  namespace QFramework {  public abstract class QSingleton
where T : QSingleton
  {    protected static T instance = null; protected QSingleton() { }   public static T Instance()   {      if (instance == null)       { // 先获取所有非public的构造方法 ConstructorInfo[] ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic); // 从ctors中获取无参的构造方法 ConstructorInfo ctor = Array.Find(ctors, c => c.GetParameters().Length == 0); if (ctor == null) throw new Exception("Non-public ctor() not found!"); // 调用构造方法 instance = ctor.Invoke(null) as T;       }     return instance;     }   } }

unity实现MonoBehaviour 单例,约束GameObject的个数,这个需求,还没有思路,只好在游戏运行时判断有多少个GameObject已经挂上了该脚本,然后如果个数大于1抛出错误即可。在脚本销毁时,把静态实例置空。 

using UnityEngine; ///  /// 需要使用Unity生命周期的单例模式 ///  namespace QFramework{   public abstract class QMonoSingleton
: MonoBehaviour where T : QMonoSingleton
  {   protected static T instance = null;    public static T Instance()     {   if (instance == null)   {  instance = FindObjectOfType
();        if (FindObjectsOfType
().Length > 1) { QPrint.FrameworkError ("More than 1!"); return instance;         } if (instance == null)         { string instanceName = typeof(T).Name; QPrint.FrameworkLog ("Instance Name: " + instanceName); GameObject instanceGO = GameObject.Find(instanceName); if (instanceGO == null) instanceGO = new GameObject(instanceName); instance = instanceGO.AddComponent
(); DontDestroyOnLoad(instanceGO); //保证实例不会被释放 QPrint.FrameworkLog ("Add New Singleton " + instance.name + " in Game!"); } else { QPrint.FrameworkLog ("Already exist: " + instance.name); } } return instance; }   protected virtual void OnDestroy()   { instance = null;   } }

 

转载于:https://www.cnblogs.com/wang-jin-fu/p/8313311.html

你可能感兴趣的文章
mysql 5.6 参数详解
查看>>
求旋转数组的最小元素
查看>>
jQuery ajax error函数(交互错误信息的获取)
查看>>
Gson解析Json数组
查看>>
Lintcode: Fast Power
查看>>
Pocket Gem OA: Log Parser
查看>>
枚举也能直接转换为对应的数值输出
查看>>
angularjs1-7,供应商
查看>>
BitSet
查看>>
Spring常用注解,自动扫描装配Bean
查看>>
(转载)深入理解WeakHashmap
查看>>
JAVA中的数组
查看>>
爬虫—使用Requests
查看>>
scrollIntoView()窗口滚动
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
使用ansible远程管理集群
查看>>
读jQuery源码释疑笔记3
查看>>
手把手教你jmeter压测--适合入门
查看>>
Sequelize+MySQL存储emoji表情
查看>>
RabbitMQ学习之Publish/Subscribe(3)
查看>>