【发布时间】: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;
}
}
}
我认为应该是这样的逻辑:
游戏从主菜单场景开始。
PLAY 按钮开始新游戏。
ESCAPE 键暂停/恢复游戏。
数字 3 按下退出键一次将返回主菜单,然后再次按下退出键将返回并从当前点恢复游戏,无论是在过场动画中间还是只是闲置游戏。
我的第一个问题是在 Main Menu 场景中获取 Main Game 对象引用。
我使用 LoadSceneMode.Additive 是因为我不想每次都加载另一个场景,而是在它们之间切换,这就是游戏场景的所有游戏对象都在 Main Game 下的原因。
【问题讨论】:
-
加载场景是一种糟糕的方式。您应该只拥有一个位于“游戏”场景中的菜单游戏对象并将其打开和关闭。只有当你真正退出游戏时,你才应该改变场景。假设甚至有必要使用整个单独的场景,但通常情况并非如此。