unity 场景的同步加载和异步加载

Note: 老版本的unity所支持的 Application.LoadLevelAsync, Application.LoadLevel 等函数已废除
同步加载两种书写形式:  
public static void  LoadScene(int  sceneBuildIndexSceneManagement.LoadSceneMode  mode = LoadSceneMode.Single);
public static void  LoadScene(string  sceneNameSceneManagement.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  sceneNameSceneManagement.LoadSceneMode  mode = LoadSceneMode.Single);
public static  AsyncOperation  LoadSceneAsync(int  sceneBuildIndexSceneManagement.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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值