版本: Unity 6 (6000.0)
语言英语
  • C#

SceneManager.SetActiveScene

建议更改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法接受所有提交内容,但我们确实阅读了用户提出的每一个建议更改,并在适用时进行更新。

关闭

提交失败

由于某种原因,您的建议更改无法提交。请<a>稍后再试</a>。感谢您抽出时间帮助我们提高 Unity 文档的质量。

关闭

取消

声明

public static bool SetActiveScene(SceneManagement.Scene scene);

参数

scene 要设置的场景。

返回值

bool 如果场景尚未加载,则返回 false。

描述

设置要激活的场景。

活动场景是将用作脚本实例化的新游戏对象的 target 的场景,以及从哪个场景使用照明设置。当您以累加方式添加场景时(参见 LoadSceneMode.Additive),第一个场景仍保留为活动场景。使用它将活动场景切换到您想要作为 target 的场景。

始终必须有一个场景标记为活动场景。请注意,活动场景对渲染哪些场景没有影响。

// Attach this script to a GameObject
// Create 2 Buttons (Create>UI>Button)
// Attach the 2 Buttons to your GameObject’s Inspector

// This script allows you to load a second Scene as an Additive Scene. Click the first Button (Load Scene Button) to load the Additive Scene. Even though the second Scene loads, the first Scene remains the active Scene. // If you press the second Button (Set Active Button), it sets the second Scene as the active Scene (and outputs the current active Scene to the console)

using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI;

public class Example : MonoBehaviour { bool m_SceneLoaded; public Button m_LoadSceneButton, m_SetActiveButton;

void Awake() { // Outputs the current active Scene to the console Debug.Log("Active Scene : " + SceneManager.GetActiveScene().name);

// Check that this Button exists if (m_LoadSceneButton != null) { // Fetch the Button from the Inspector. Make sure to set this in the Inspector window Button loadButton = m_LoadSceneButton.GetComponent<Button>();

// Call the LoadScene2Button() function when this Button is clicked loadButton.onClick.AddListener(LoadSceneButton); }

if (m_SetActiveButton != null) { Button buttonTwo = m_SetActiveButton.GetComponent<Button>(); buttonTwo.onClick.AddListener(SetActiveSceneButton); } }

// Load the Scene when this Button is pressed void LoadSceneButton() { // Check that the second Scene hasn't been added yet if (m_SceneLoaded == false) { // Loads the second Scene SceneManager.LoadScene("Scene2", LoadSceneMode.Additive);

// Outputs the name of the current active Scene. // Notice it still outputs the name of the first Scene Debug.Log("Active Scene : " + SceneManager.GetActiveScene().name);

// The Scene has been loaded, exit this method m_SceneLoaded = true; } }

// Change the newly loaded Scene to be the active Scene if it is loaded void SetActiveSceneButton() { // Allow this other Button to be pressed when the other Button has been pressed (Scene 2 is loaded) if (m_SceneLoaded == true) { // Set Scene2 as the active Scene SceneManager.SetActiveScene(SceneManager.GetSceneByName("Scene2"));

// Ouput the name of the active Scene // See now that the name is updated Debug.Log("Active Scene : " + SceneManager.GetActiveScene().name); } } }