Unity - 如何在不同场景中正确引用GameManager

Unity - How to properly reference the GameManager in different scenes

我是 Unity 的新手,正在开始创建我的第一个简单项目。几天来我一直面临一个问题并进行了大量研究,但我仍然无法让它工作,就是这样:

据我所知,拥有一个包含游戏主要功能的“GameManager”脚本的“GameManager”对象是一个明智的想法(如果不是最佳做法,请纠正我)。举个例子,我有场景 1 和场景 2:

场景 1: -游戏经理 -标签

在 GameManager 中有一个名为 ChangeLabelText() 的函数

场景二: -按钮 -Scene2Script

在 Scene2script 中有一个名为 ButtonOnClick() 的函数

这是我的问题:如何让 ButtonOnClick() 调用 GameManager.ChangeLabelText()? 我总是收到参考错误。

我试过在同一个场景中完成它并且它完美地工作,但不是在不同的场景之间。 有什么想法吗?

谢谢!

在 Unity 中更改场景会导致 Unity 销毁每个实例。如果你想在多个场景中保留特定的 instance/GameObject,你可以使用 DontDestroyOnLoad 方法。您可以传递游戏对象,这个特定的 GameManager 实例作为参数附加到。您可能也想使用单例模式,原因有二:

  • 您可能不希望同时拥有两个或更多 GameManager class 实例。单例会阻止这种情况。
  • 尽管如此,您必须找到一种方法来引用此实例,因为您的其他 class 中的组件是全新的实例,它们不知道此 GameManager 组件在哪里。

单例模式示例:

GameManager.cs

public static GameManager Instance; // A static reference to the GameManager instance

void Awake()
{
    if(Instance == null) // If there is no instance already
    {
        DontDestroyOnLoad(gameObject); // Keep the GameObject, this component is attached to, across different scenes
        Instance = this;
    } else if(Instance != this) // If there is already an instance and it's not `this` instance
    {
        Destroy(gameObject); // Destroy the GameObject, this component is attached to
    }
}

Example.cs

private GameManager gameManager;

void Start() // Do it in Start(), so Awake() has already been called on all components
{
    gameManager = GameManager.Instance; // Assign the `gameManager` variable by using the static reference
}

这当然只是基本原理。如果需要,您可以将其应用于各种略有不同的变体。