微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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

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

在 GameManager 中有一个函数叫做 ChangeLabelText()

场景2: -按钮 -Scene2Script

在 Scene2script 中有一个函数叫做 ButtonOnClick()

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

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

谢谢!

解决方法

在 Unity 中更改场景会导致 Unity 破坏每个实例。如果您想在多个场景中保留一个特定的实例/游戏对象,您可以使用 DontDestroyOnLoad 方法。您可以传递游戏对象,这个特定的 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
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。