Version: 2017.3
public static void LoadScene (int sceneBuildIndex, SceneManagement.LoadSceneMode mode= LoadSceneMode.Single);
public static void LoadScene (string sceneName, SceneManagement.LoadSceneMode mode= LoadSceneMode.Single);

参数

sceneName 要加载的场景的名称或路径。
sceneBuildIndex Build Settings 中要加载场景的索引。
mode 允许您指定是否以叠加方式加载场景。 请参阅 LoadSceneMode,了解有关选项的更多信息。

描述

按照 Build Settings 中的名称或索引加载场景。

注意:在大多数情况下,为了避免在加载时出现暂停或性能中断现象, 您应该使用此命令的异步版,即: LoadSceneAsync

使用 SceneManager.LoadScene时,系统将不会 立即加载场景,而是会在下一帧完成加载。这种半异步的行为 可能会导致帧卡顿,并可能令人困惑,因为加载无法 立即完成。

Important: Since loading is set to complete in the next rendered frame, calling SceneManager.LoadScene forces all previous AsynOperations to complete, even if AsyncOperation.allowSceneActivation is set to false. This can be avoided by using LoadSceneAsync instead.

提供的 sceneName 可以只是场景名称(不包含 .unity 扩展名),也可以是 Build Settings 窗口中显示的路径(仍然不包含 .unity 扩展名)。如果仅提供场景名称,此方法将加载匹配的场景列表中的 第一个场景。如果您有多个名称相同但路径不同的场景, 应该使用完整的路径。

请注意,除非您从 AssetBundle 加载场景,否则 sceneName 不区分大小写。

如需在编辑器中打开场景,请参阅 EditorSceneManager.OpenScene

using UnityEngine;
using UnityEngine.SceneManagement;

public class ExampleClass : MonoBehaviour { void Start() { // Only specifying the sceneName or sceneBuildIndex will load the Scene with the Single mode SceneManager.LoadScene("OtherSceneName", LoadSceneMode.Additive); } }
// Load an assetbundle which contains Scenes.
// When the user clicks a button the first Scene in the assetbundle is
// loaded and replaces the current Scene.

using UnityEngine; using UnityEngine.SceneManagement;

public class LoadScene : MonoBehaviour { private AssetBundle myLoadedAssetBundle; private string[] scenePaths;

// Use this for initialization void Start() { myLoadedAssetBundle = AssetBundle.LoadFromFile("Assets/AssetBundles/scenes"); scenePaths = myLoadedAssetBundle.GetAllScenePaths(); }

void OnGUI() { if (GUI.Button(new Rect(10, 10, 100, 30), "Change Scene")) { Debug.Log("Scene2 loading: " + scenePaths[0]); SceneManager.LoadScene(scenePaths[0], LoadSceneMode.Single); } } }

下面两个脚本示例显示了 LoadScene 可以如何从 Build Settings 加载场景。LoadSceneA 使用场景名称加载场景,LoadSceneB 则使用场景编号加载场景。两个脚本配合使用。

LoadSceneA 文件。

// SceneA.
// SceneA is given the sceneName which will
// load SceneB from the Build Settings

using UnityEngine; using UnityEngine.SceneManagement;

public class LoadScenesA : MonoBehaviour { void Start() { Debug.Log("LoadSceneA"); }

public void LoadA(string scenename) { Debug.Log("sceneName to load: " + scenename); SceneManager.LoadScene(scenename); } }

LoadSceneB 文件。

// SceneB.
// SceneB is given the sceneBuildIndex of 0 which will
// load SceneA from the Build Settings

using UnityEngine; using UnityEngine.SceneManagement;

public class LoadScenesB : MonoBehaviour { void Start() { Debug.Log("LoadSceneB"); }

public void LoadB(int sceneANumber) { Debug.Log("sceneBuildIndex to load: " + sceneANumber); SceneManager.LoadScene(sceneANumber); } }