当前位置: 首页 > news >正文

[Unity] 单例设计模式, 可供继承的单例组件模板类

一个可供继承的单例组件模板类:

public class SingletonComponent<TComponent> : Componentwhere TComponent : SingletonComponent<TComponent>
{static TComponent _instance;private static TComponent GetOrFindOrCreateComponent(){// 双检索if (_instance == null){// 尝试在场景中查找已存在的组件_instance = FindObjectOfType<TComponent>();// 如果找不到, 则创建一个空对象, 并且挂载上组件if (_instance == null){GameObject gameObject = new GameObject();_instance = gameObject.AddComponent<TComponent>();}}return _instance;}public static TComponent Instance => GetOrFindOrCreateComponent();
}

因为 Unity 是单线程的, 所以在这里没有必要使用双检索


使用方式

例如你要创建一个全局的单例管理类, 可以这样使用:

public class GameManager : SingletonComponent<GameManager>
{// your code here
}

注意事项

尽量避免让 SingletonComponent 帮你创建组件, 因为它只是单纯的将组件创建, 并挂载到空对象上, 而不会进行任何其他行为. 如果你的组件需要进行某些初始化, 那么它可能不会正常.

http://www.lryc.cn/news/143803.html

相关文章:

  • Linux知识点 -- Linux多线程(三)
  • android java 硬编码保存mp4 jni数据转换
  • 那些你不得不知道的HTML知识点
  • 如何复制主播的性格(此乃广告文)
  • 【ES6】—【新特性】—Symbol详情
  • openresty安装与网站发布
  • 创建延时队列、springboot配置多个rabbitmq
  • 在kaggle中用GPU使用CGAN生成指定mnist手写数字
  • 【NI USRP】哪些 USRP 设备支持全双工,哪些支持半双工?
  • 不拼花哨,只拼实用:unittest指南,干货为王!
  • mysql 获取json数组中某个字段根据下标
  • 深入理解Redis缓存穿透、击穿、雪崩及解决方案
  • java八股文面试[java基础]——字节码
  • 新能源汽车技术的最新进展和未来趋势
  • 知虾shopee数据分析工具:shopee出单的商机利器
  • python——ydata-profiling介绍与使用
  • (纯c)数据结构之------>链表(详解)
  • postman接口自动化测试框架实战!
  • Apache Doris 入门教程35:多源数据目录
  • 响应式web-PC端web与移动端web(H5)兼容适配 选型方案
  • Redis持久化之RDB解读
  • 四维图新 minemap实现地图漫游效果
  • centos7安装MySQL8
  • 【IMX6ULL驱动开发学习】10.Linux I2C驱动实战:AT24C02驱动设计流程
  • 【C++】详解声明和定义
  • 掌握C/C++协程编程,轻松驾驭并发编程世界
  • MyBatis-Plus的分页配置类
  • 排序算法-选择排序(Java)
  • SpringBoot 怎么返回html界面
  • watch computed 和 method