简介
加载场景的重载函数如下:
代码语言:javascript复制/// <summary>
/// 异步加载场景
/// </summary>
/// <param name="sceneName">场景名称</param>
/// <param name="sceneActivationDelay">激活延迟时长</param>
/// <param name="loadSceneMode">场景加载方式</param>
/// <returns></returns>
public static SceneLoader LoadAsync(string sceneName, float sceneActivationDelay = 3f, LoadSceneMode loadSceneMode = LoadSceneMode.Single)
/// <summary>
/// 异步加载场景
/// </summary>
/// <param name="sceneBuildIndex">场景指针</param>
/// <param name="sceneActivationDelay">激活延迟时长</param>
/// <param name="loadSceneMode">场景加载方式</param>
/// <returns></returns>
public static SceneLoader LoadAsync(int sceneBuildIndex, float sceneActivationDelay = 3f, LoadSceneMode loadSceneMode = LoadSceneMode.Single)
其中sceneActivationDelay参数表示当场景在内存中加载完成时,需要延迟该时长才允许场景激活,原理是首先将异步操作AsyncOperation中的allowSceneActivation设为false,在场景加载完成并延迟后再将其设为true,该参数默认值为3。
loadSceneMode表示加载场景的方式,默认值为Single,表示覆盖当前场景,Additive则表示场景叠加到当前场景。
一、通过名称加载场景
代码语言:javascript复制using UnityEngine;
using SK.Framework;
public class Example : MonoBehaviour
{
private void Start()
{
//加载名为Example的场景
SceneLoader.LoadAsync("Example", 5f);
}
}
代码语言:javascript复制using UnityEngine;
using SK.Framework;
using UnityEngine.SceneManagement;
public class Example : MonoBehaviour
{
private void Start()
{
//加载名为Example的场景
SceneLoader.LoadAsync("Example", 0f, LoadSceneMode.Additive);
}
}
二、通过指针加载场景
代码语言:javascript复制using UnityEngine;
using SK.Framework;
public class Example : MonoBehaviour
{
private void Start()
{
//加载BuildIndex为1的场景
SceneLoader.LoadAsync(1);
}
}
三、事件
场景加载事件包含开始事件、加载中事件、完成事件,通过如下方式设置:
代码语言:javascript复制using UnityEngine;
using SK.Framework;
public class Example : MonoBehaviour
{
private void Start()
{
//加载名为Example的场景
SceneLoader.LoadAsync("Example", 5f)
.OnBegan(() => Debug.Log("开始加载"))
.OnLoading(progress => Debug.Log(string.Format("加载进度 {0}", progress)))
.OnCompleted(() => Debug.Log("加载完成"));
}
}
代码语言:javascript复制四、示例
代码语言:javascript复制using UnityEngine;
using SK.Framework;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Example : MonoBehaviour
{
//场景加载过度界面
[SerializeField] GameObject loadingView;
//加载进度条
[SerializeField] Image progress;
//加载进度文本
[SerializeField] Text progressText;
private void Start()
{
//加载名为Example的场景
SceneLoader.LoadAsync("Example", 5f, LoadSceneMode.Additive)
.OnBegan(() => loadingView.SetActive(true))
.OnLoading(s =>
{
progress.fillAmount = s;
progressText.text = string.Format("{0}%", Mathf.Round(s * 100));
})
.OnCompleted(() => loadingView.SetActive(false));
}
}
效果: