【问题标题】:How can I get a reference for a gameobject from another scene?如何从另一个场景中获取游戏对象的参考?
【发布时间】:2020-01-31 04:30:05
【问题描述】:

我有两个场景。主菜单和游戏场景。 我游戏的所有对象都在一个名为 Main Game 的父游戏对象下。 并且该对象在运行游戏时被禁用。首先是主菜单场景。

当我单击主菜单中的 PLAY 按钮时,我想将另一个场景中的 Main Game 对象设置为 active。

此脚本附加到主菜单游戏对象:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MainMenu : MonoBehaviour
{
    public void PlayGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1, LoadSceneMode.Additive);

        var mainGame = GameObject.FindGameObjectWithTag("Main Game");
        mainGame.SetActive(true);
    }

    public void QuitGame()
    {
        Application.Quit();
    }
}

我尝试使用 FindGameObjectWithTag,但 var mainGame 为空。

这个脚本附加到返回主菜单游戏对象:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class BackToMainMenu : MonoBehaviour
{
    // Variables
    private bool _isInMainMenu = false;
    public GameObject mainGame;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (!_isInMainMenu)
            {
                SceneManager.LoadScene(0, LoadSceneMode.Additive);

                // -- Code to freeze the game
                mainGame.SetActive(false);
            }
            else
            {
                SceneManager.UnloadSceneAsync(0);
                // -- Code to unfreeze the game
                mainGame.SetActive(true);
            }

            _isInMainMenu = !_isInMainMenu;
        }
    }
}

我认为应该是这样的逻辑:

  1. 游戏从主菜单场景开始。

  2. PLAY 按钮开始新游戏。

  3. ESCAPE 键暂停/恢复游戏。

数字 3 按下退出键一次将返回主菜单,然后再次按下退出键将返回并从当前点恢复游戏,无论是在过场动画中间还是只是闲置游戏。

我的第一个问题是在 Main Menu 场景中获取 Main Game 对象引用。

我使用 LoadSceneMode.Additive 是因为我不想每次都加载另一个场景,而是在它们之间切换,这就是游戏场景的所有游戏对象都在 Main Game 下的原因。

【问题讨论】:

  • 加载场景是一种糟糕的方式。您应该只拥有一个位于“游戏”场景中的菜单游戏对象并将其打开和关闭。只有当你真正退出游戏时,你才应该改变场景。假设甚至有必要使用整个单独的场景,但通常情况并非如此。

标签: c# unity3d


【解决方案1】:

丹尼尔,

实现此目的的一种方法是提供对 Main Game 对象的静态引用。这将可以跨场景访问。例如,

using UnityEngine;

public class GameManager: MonoBehaviour
{
    [SerializeField]
    private GameObject mainGame;

    public static GameObject MainGame {get;private set;}

    void Awake(){
        GameManager.MainGame = mainGame;
    }

}

现在您可以通过 GameManager.MainGame 引用 MainMenu 脚本中的 mainGame 对象

【讨论】:

  • 这是有效的。但现在我有另一个问题。由于两个场景都已经在层次结构中,我想在点击播放按钮时节省加载时间,它会再次加载场景很多次。按下 ESCAPE 键时也是如此。如果我不使用 LoadSceneMode.Additive,它将在激活主游戏对象之前删除主菜单。
  • @NickPfister 我不太明白你的答案,它需要一些例子。
猜你喜欢
  • 2017-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-18
相关资源
最近更新 更多