当前位置:网站首页>学习(二):单例模板
学习(二):单例模板
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);
}
}
}
边栏推荐
猜你喜欢

联阳(ITE)IT66021FN:HDMI转RGB芯片 3D 资料

Beckhoff ET2000 listener use

【详解】线程池及其自定义线程池的实现

全加器高进位和低进位的理解

实现动态库(DLL)之间内存统一管理

HDMI转MIPI CSI东芝转换芯片-TC358743XBG/TC358749XBG

【MQ-3 Alcohol Detector and Arduino Detect Alcohol】

Basic IO (below): soft and hard links and dynamic and static libraries

所有子字符串中的元音 —— LeetCode - 2063

AD实战篇
随机推荐
剑指Offer 34.二叉树中和为某一值的路径 dfs+回溯
IDEA2021.2安装与配置(持续更新)
Beckhoff ET2000 listener use
UKlog.dat和QQ,微信文件的转移
只出现一次的字符
MQ-5 combustible gas sensor interface with Arduino
剑指Offer 47.礼物的最大值 动态规划
Basic IO (below): soft and hard links and dynamic and static libraries
idea中创建jsp项目详细步骤
bluez5.50+pulseaudio实现蓝牙音响音频播放
【数据库】事务的四大特性<详解>
IoT solution
STM32 CAN 介绍以及相关配置
Lightly 支持 Markdown 文件在线编写(文中提供详细 Markdown 语法)
剑指Offer 32.Ⅱ从上到下打印二叉树
openwrt RK3568_EVB移植
2020 - AAAI - Image Inpainting论文导读《Learning to Incorporate Structure Knowledge for Image Inpainting》
向龙芯2K1000板子上烧写中标麒麟系统
78XX 79XX多路输出电源
list:list的介绍和模拟实现