介绍
有大量的编程模式和反模式。模式的使用通常指示我们自己的经验和实际知识。在本文中,我想与您讨论Singleton模式的应用,即在Net中应用于Unity的实现。
辛格尔顿
我注意到我是在团队中编写代码,因此我在代码内部进行了尽可能多的工作,以减轻团队负担并消除考虑在Unity中实现某些模式的一些困难。
研究有关该问题2的网络1的文献,并通过几个项目的工作,诞生了以下课程:
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
private static T instance = null;
private bool alive = true;
public static T Instance
{
get
{
if (instance != null)
{
return instance;
}
else
{
T[] managers = GameObject.FindObjectsOfType<T>();
if (managers != null)
{
if (managers.Length == 1)
{
instance = managers[0];
DontDestroyOnLoad(instance);
return instance;
}
else
{
if (managers.Length > 1)
{
Debug.LogError($"Have more that one {typeof(T).Name} in scene. " +
"But this is Singleton! Check project.");
for (int i = 0; i < managers.Length; ++i)
{
T manager = managers[i];
Destroy(manager.gameObject);
}
}
}
}
GameObject go = new GameObject(typeof(T).Name, typeof(T));
instance = go.GetComponent<T>();
instance.Initialization();
DontDestroyOnLoad(instance.gameObject);
return instance;
}
}
set
{
instance = value as T;
}
}
public static bool IsAlive
{
get
{
if (instance == null)
return false;
return instance.alive;
}
}
protected void Awake()
{
if (instance == null)
{
DontDestroyOnLoad(gameObject);
instance = this as T;
Initialization();
}
else
{
Debug.LogError($"Have more that one {typeof(T).Name} in scene. " +
"But this is Singleton! Check project.");
DestroyImmediate(this);
}
}
protected void OnDestroy() { alive = false; }
protected void OnApplicationQuit() { alive = false; }
protected virtual void Initialization() { }
}
我将集中在几个方面。
对象创建
在扩展项目时,尤其是团队合作> 3人时,创建对象的顺序不清楚的情况经常会出现。严格来说3,对Awake()的调用顺序是随机的(当然,这并非完全正确,并且可以影响该过程,但是文档是神圣的),这就是为什么有必要通过实现Instance {get;}属性来消除此烦人的缺点的原因。结果,我们可以从其他类的Awake()完全访问单例。
, Lazy, Awake() .
4-4, , Instance{get;}.
Unity — Awake(). , , Initialization(). (KISS).
, DI SD. . .
, , OnDestroy(), OnApplicationQuit() 5:
Did you spawn new GameObjects from OnDestroy?
, , , . , IsAlive(), , . , ...
我越来越多地得出结论,使用Unity范例可以在没有Singleton的情况下实现我的项目。通常,应用此模式会使您的代码高度连接且极其脆弱。
谢谢。
资料来源
-Richter J.“通过C#进行CLR。在C#中使用Microsoft.NET#Framework 4.5编程”,2013年
- https://www.codingame.com/playgrounds/1979/different-ways-to-implement-singleton-in--net-and-make-people-hate-you-along-the-way
- https://docs.unity3d.com/en/current/ScriptReference/MonoBehaviour.Awake.html
- https://ru.wikipedia.org/wiki/Design_Patterns
-Dickinson Chris,《 Unity 2017游戏优化,第二版》,2017年