Note: 老版本的unity所支持的 Application.LoadLevelAsync, Application.LoadLevel 等函数已废除
同步加载,两种书写形式:
public static void
LoadScene(int
sceneBuildIndex,
SceneManagement.LoadSceneMode
mode = LoadSceneMode.Single);
public static void
LoadScene(string
sceneName,
SceneManagement.LoadSceneMode
mode = LoadSceneMode.Single);
参数sceneBuildIndex代表在Building setting时加载的场景的顺序序号;sceneName代表待加载场景的名称或路径;mode代表加载场景的方式,
有Single(只显示新加载的场景)和Additive(在原场景的基础上加载新场景)两种。
说明:使用scenemanager.loadscene时,加载不会立即发生,而是完成在下一帧。正是因为这种半异步的表现才导致了加载场景时帧与帧之间的不流畅。由于加载是完成在下一帧里,即使AsyncOperation.allowSceneActivation被设置成false,调用scenemanager.loadscene时也会强制所有之前的AsynOperations完成。故多数情况下,为了避免场景加载期间产生的卡顿,应该使用异步加载命令。
举例如下:
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); } }
异步加载,
两种书写方式:
public static
AsyncOperation
LoadSceneAsync(string
sceneName,
SceneManagement.LoadSceneMode
mode = LoadSceneMode.Single);
public static
AsyncOperation
LoadSceneAsync(int
sceneBuildIndex,
SceneManagement.LoadSceneMode
mode = LoadSceneMode.Single);
返回值类型为AsyncOperation,用以确定加载是否完成;其他参数与同步加载的参数含义保持一致。
说明:场景的名称(sceneName)可以不区分大小写。
举例如下:
using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; public class Example : MonoBehaviour { void Update() { // Press the space key to start coroutine if (Input.GetKeyDown(KeyCode.Space)) { // Use a coroutine to load the Scene in the background StartCoroutine(LoadYourAsyncScene()); } } IEnumerator LoadYourAsyncScene() { // The Application loads the Scene in the background as the current Scene runs. // This is particularly good for creating loading screens. // You could also load the Scene by using sceneBuildIndex. In this case Scene2 has // a sceneBuildIndex of 1 as shown in Build Settings. AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Scene2"); // Wait until the asynchronous scene fully loads while (!asyncLoad.isDone) { yield return null; } } }
参考官网:
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html