[英]Singleton Design Pattern question Unity3D
I have some codes below我在下面有一些代码
[SerializeField] int playerLives = 3;
void Awake()
{
int numGameSessions = FindObjectsOfType<GameSession>().Length;
if(numGameSessions > 1)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
Explain situation:说明情况:
In your example, when you have 3 items when the first Awake starts all the 3 Game Sessions are already attached to the scene, so it will destroy all GameSession objects.在您的示例中,当第一个 Awake 开始时您有 3 个项目时,所有 3 个游戏会话都已附加到场景中,因此它将销毁所有 GameSession 对象。 This is not the right way to do Singleton pattern in Unity.
这不是在 Unity 中执行 Singleton 模式的正确方法。 A better approach would be:
更好的方法是:
using UnityEngine;
public class Singleton : MonoBehaviour {
private static Singleton instance;
public Singleton Instance { get { return instance; } }
void Awake() {
if (instance == null) {
instance = this;
DontDestroyOnLoad(this.gameObject);
} else {
Destroy(this);
}
}
}
you can then get your instance by calling Singleton.Instance
然后,您可以通过调用
Singleton.Instance
来获取您的实例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.