简体   繁体   English

Singleton 设计模式问题 Unity3D

[英]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:说明情况:

  • First I have one obj in my hierarchy like this首先,我的层次结构中有一个像这样的 obj 在此处输入图像描述 and then the Don't Destroy On Load appears, and the game works normally.然后出现Don't Destroy On Load,游戏正常运行。
  • But when I put 3 Game Session into my Scene, all disappear and the Don't Destroy On Load doesn't appear, why does this happen?但是当我将 3 Game Session 放入我的场景中时,所有游戏都消失了,并且没有出现 Don't Destroy On Load,为什么会出现这种情况?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM