这只是一个在Unity上困扰我的问题。
我们经常使用单例对象,比如游戏管理器等等,有两种方法可以做到这一点。
一种是使用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;
}
}但我认为,这就像是一次又一次地编写相同的代码。有没有人能建议一种更干净的方法呢?
发布于 2017-09-19 11:59:01
我不确定您到底想要什么,但在单例模式中,我更喜欢创建一个像GameManager这样的主类,并使用下面这段代码将其设置为单例类:
static GameManager _instance;
public static GameManager instance {
get {
if (!_instance) {
_instance = FindObjectOfType<GameManager>();
}
return _instance;
}
}或者你写的那段代码,然后根据其他子管理器类型定义变量,并通过GameManager单例访问它们。
例如:
public BulletManager myBulletManager;并像这样使用它:
GameManager.instance.myBulletManager.Fire();https://stackoverflow.com/questions/46286996
复制相似问题