Unity Singleton Pattern(Unity单件模式)
本文介绍了Unity单件模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这只是一个困扰我关于Unity的问题。
我们经常使用游戏管理器等Singleton对象,为此有两种方法。
一种是使用Singleton.cs c Sharp类,如下所示:
using System;
using System.Linq;
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
static T instance;
DateTime BirthTime;
public static T Instance
{
get
{
if (instance == null)
Initialize();
return instance;
}
}
private void Awake()
{
BirthTime = DateTime.Now;
}
public static void Initialize()
{
if (instance == null)
instance = FindObjectOfType<T>();
}
}
然后将GameManager派生为
GamaManager : Singleton<GameManager>
在大众看来,这种方法很消耗CPU,尤其是在移动设备上,因为Unity要使用Singleton中提到的Initialize方法,必须遍历这么多对象的层次结构。
更简单的方法是创建私有实例,并在启动或唤醒时将其初始化为:
GameManager : MonoBehaviour
{
public static GameManager Instance { get; private set; }
void Start()
{
Instance = this;
}
}
但我认为,这就像是一次又一次地编写相同的代码。有没有人能建议一种更干净的方法来解决这个问题?
推荐答案
我不确定您到底想要什么,但在单例模式中,我更喜欢创建一个像GameManager这样的主类,并使用下面这段代码将其设置为单例类:
static GameManager _instance;
public static GameManager instance {
get {
if (!_instance) {
_instance = FindObjectOfType<GameManager>();
}
return _instance;
}
}
或您编写的代码,之后根据其他子管理器类型定义变量,并由GameManager单例访问。
例如:
public BulletManager myBulletManager;
按如下方式使用:
GameManager.instance.myBulletManager.Fire();
这篇关于Unity单件模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:Unity单件模式
基础教程推荐
猜你喜欢
- 如果条件可以为空 2022-01-01
- 将数据集转换为列表 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
