Unity通用泛型单例设计模式(普通型和继承自MonoBehaviour)
单例模式是设计模式中最为常见的,不多解释了。但应该尽量避免使用,一般全局管理类才使用单例。
普通泛型单例:
publicabstractclassSingletonwhereT:class,new() { privatestaticTinstance=null; privatestaticreadonlyobjectlocker=newobject(); publicstaticTInstance { get { lock(locker) { if(instance==null) instance=newT(); returninstance; } } } }
继承MonoBehaviour的泛型单例:
usingUnityEngine; publicabstractclassMonoSingleton:MonoBehaviourwhereT:MonoBehaviour { privatestaticTinstance=null; privatestaticreadonlyobjectlocker=newobject(); privatestaticboolbAppQuitting; publicstaticTInstance { get { if(bAppQuitting) { instance=null; returninstance; } lock(locker) { if(instance==null) { instance=FindObjectOfType (); if(FindObjectsOfType ().Length>1) { Debug.LogError("不应该存在多个单例!"); returninstance; } if(instance==null) { varsingleton=newGameObject(); instance=singleton.AddComponent (); singleton.name="(singleton)"+typeof(T); singleton.hideFlags=HideFlags.None; DontDestroyOnLoad(singleton); } else DontDestroyOnLoad(instance.gameObject); } instance.hideFlags=HideFlags.None; returninstance; } } } privatevoidAwake() { bAppQuitting=false; } privatevoidOnDestroy() { bAppQuitting=true; } }
使用方法直接用类去继承这两个抽象单例即可,使用T.Instance就可以直接取得该类(T)的唯一实例了。
以上就是Unity通用泛型单例设计模式(普通型和继承自MonoBehaviour)的详细内容,更多关于unity单例设计模式的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。