【问题标题】:Unity - How to properly reference the GameManager in different scenes [duplicate]Unity - 如何在不同场景中正确引用 GameManager [重复]
【发布时间】:2021-04-16 10:56:34
【问题描述】:

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

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

场景1: -游戏管理器 -标签

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

场景2: -按钮 -Scene2Script

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

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

我尝试在同一个场景中执行此操作,并且效果很好,但在不同场景之间却不行。 有什么想法吗?

谢谢!

【问题讨论】:

  • 这是因为当你过渡到 Scene2 时,scene1 中的 GameManager 实例“死亡”,所以它不再可用。为了解决这个问题,在 GameManager 的 Awake/Start 函数中添加“DontDestroyOnLoad”。

标签: c# unity3d game-development


【解决方案1】:

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

  • 您可能不想同时拥有两个或多个 GameManager 类的实例。单身人士会阻止这种情况。
  • 尽管如此,您必须找到一种方法来引用此实例,因为您的其他类中的组件是全新的实例,它们不知道此 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
    }
}

示例.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
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多