当前位置:网站首页>学习(二):单例模板
学习(二):单例模板
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
- 滑动窗口方法
- 如何搭建私有云盘?
- MPU6050 accelerometer and gyroscope sensor is connected with the Arduino
- Process (present) : custom shell command line interpreter
- path 修补文件命令
- unity 代码拆分图集
- Comparative analysis of OneNET Studio and IoT Studio
- HAL库笔记——通过按键来控制LED(基于正点原子STM32F103ZET6精英板)
- TC358860XBG BGA65 东芝桥接芯片 HDMI转MIPI
猜你喜欢
随机推荐
引擎开发日志:集成Bullet3物理引擎
Laptop charging problems
Altium Designer Basics
AD Actual Combat
使用buildroot制作根文件系统(龙芯1B使用)
idea中创建jsp项目详细步骤
Arduino lights up nixie tubes
Hash table problem solving method
vector的使用和模拟实现:
调试九法准则
78XX 79XX多路输出电源
实现动态库(DLL)之间内存统一管理
【plang 1.4.5】编写坦克(双人)游戏脚本
NE5532运放加法器
回溯法 & 分支限界 - 2
【面试必看】链表的常见笔试题
LL(1)文法 :解决 if-else/if-else 产生式二义性问题
机械臂运动学解析
所有子字符串中的元音 —— LeetCode - 2063
IDEA2021.2安装与配置(持续更新)









