当前位置:网站首页>学习(二):单例模板
学习(二):单例模板
2022-08-02 03:34:00 【落水无痕】
Singleton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 实现普通的单例模式
// where 限制模板的类型, new()指的是这个类型必须要能被实例化
public abstract class Singleton<T> where T : new() {
private static T _instance;
private static object mutex = new object();
public static T Instance {
get {
if (_instance == null) {
lock (mutex) { // 保证我们的单例,是线程安全的;
if (_instance == null) {
_instance = new T();
}
}
}
return _instance;
}
}
}
// Monobeavior: 声音, 网络
// Unity单例
public class UnitySingleton<T> : MonoBehaviour
where T : Component {
private static T _instance = null;
public static T Instance {
get {
if (_instance == null) {
_instance = FindObjectOfType(typeof(T)) as T;
if (_instance == null) {
GameObject obj = new GameObject();
_instance = (T)obj.AddComponent(typeof(T));
obj.hideFlags = HideFlags.DontSave;
// obj.hideFlags = HideFlags.HideAndDontSave;
obj.name = typeof(T).Name;
}
}
return _instance;
}
}
public virtual void Awake() {
DontDestroyOnLoad(this.gameObject);
if (_instance == null) {
_instance = this as T;
}
else {
GameObject.Destroy(this.gameObject);
}
}
}
边栏推荐
- Lightly 支持 Markdown 文件在线编写(文中提供详细 Markdown 语法)
- TC358860XBG BGA65 东芝桥接芯片 HDMI转MIPI
- 振芯科技GM8285C:功能TTL转LVDS芯片简介
- 进程(下):进程控制、终止、等待、替换
- 【数据库】事务的四大特性<详解>
- GM8775C MIPI转LVDS调试资料分享
- WebApp 在线编程成趋势:如何在 iPad、Matepad 上编程?
- 【plang 1.4.3】定时器的使用
- VCA821可变增益放大器
- MPU6050 accelerometer and gyroscope sensor is connected with the Arduino
猜你喜欢

idea中创建jsp项目详细步骤

ICN6211:MIPI DSI转RGB视频转换芯片方案介绍 看完涨知识了呢

rosdep update failure solution (pro-test effective)

Comparative analysis of mobile cloud IoT pre-research and Alibaba Cloud development

proteus数字电路仿真——入门实例

R语言 —— 多元线性回归

Beckhoff ET2000 listener use

如何用 Lightly 进行 Debug 断点调试?

IoT solution

【详解】优先级队列的底层实现
随机推荐
【LeetCode】求和
【plang 1.4.6】Plang高级编程语言(发布)
Comparative analysis of OneNET Studio and IoT Studio
使用飞凌嵌入式IMX6UL-C1板子——qt+opencv环境搭建
学习(四):显示FPS,和自定义显示调试
笔记本电脑充电问题
电子密码锁_毕设‘指导’
LT8918L LVDS转MIPI芯片技术支持资料
引擎开发日志:重构骨骼动画系统
rosdep update failure solution (pro-test effective)
proteus数字电路仿真——入门实例
NE5532运放加法器
IDEA2021.2安装与配置(持续更新)
【LeetCode】链表相加 进位
振芯科技GM8285C:功能TTL转LVDS芯片简介
Chrome 里的小恐龙游戏是怎么做出来的?
GM8284DD,GM8285C,GM8913,GM8914,GM8905C,GM8906C,国腾振芯LVDS类芯片
vector的使用和模拟实现:
AD Actual Combat
进程(中):进程状态、进程地址空间