当前位置:网站首页>学习(二):单例模板
学习(二):单例模板
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);
}
}
}
边栏推荐
- Based on the raspberry pie smart luggage development environment set up
- unity 代码拆分图集
- LT8918L LVDS转MIPI芯片技术支持资料
- GM7150 CVBS转BT656视频解码芯片详细内容及设计要求
- 实现动态库(DLL)之间内存统一管理
- Pylon CLI 低成本的本地环境管控工具应用实例
- 【多线程】线程安全保护机制
- 龙讯LT6911系列C/UXC/UXB/GXC/GXB芯片功能区别阐述
- Altium Designer基础知识
- GM7150,振芯科技,视频解码器,CVBS转BT656/601,QFN32,替换TVP5150/CJC5150
猜你喜欢
随机推荐
【Connect the heart rate sensor to Arduino to read the heart rate data】
vector的使用和模拟实现:
WebApp 在线编程成趋势:如何在 iPad、Matepad 上编程?
Hash table problem solving method
rosdep update failure solution (pro-test effective)
使用pyqt弹出消息提示框
开源代码交叉编译操作流程及遇到的问题解决(lightdm)
bluez5.50+pulseaudio实现蓝牙音响音频播放
AD实战篇
IoT solution
【plang 1.4.4】编写贪吃蛇脚本
Process (in): process state, process address space
bluez5.50蓝牙文件传输
install 命令
振芯科技GM8285C:功能TTL转LVDS芯片简介
剑指Offer 64.求1+2+...+n 递归+&&
GM8775C规格书,MIPI转LVDS,MIPI转双路LVDS分享
Anaconda(Jupyter)里发现不能识别自己的GPU该怎么办?
AD8361检波器
如何搭建私有云盘?









