实现异步加载场景不仅需要当前场景和目标场景,同时还需要一个中间场景实现目标场景的加载过程。
对于中间场景的构建可添加进度条(slider组件)和进度显示(Text组件)。同时在MainCamera上挂在脚本内容如下:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class SceneControl
{
public static string targetSceneName;
public static void LoadScene(string sceneName)
{
targetSceneName = sceneName;
SceneManager.LoadScene("MiddleScene");
}
}
public class LoadScene : MonoBehaviour
{
//将Slider组件拖入此位置
public Slider loadingSlider;
//将Text组件拖入此位置
public Text loadingText;
private float loadingSpeed = 0.4f;
private float targetValue;
private AsyncOperation operation;
// Use this for initialization
void Start()
{
StartCoroutine(AsyncLoading());
}
IEnumerator AsyncLoading()
{
operation = SceneManager.LoadSceneAsync(SceneControl.targetSceneName);
//阻止当加载完成自动切换
operation.allowSceneActivation = false;
yield return operation;
}
// Update is called once per frame
void Update()
{
targetValue = operation.progress;
if (operation.progress >= 0.9f)
{
//operation.progress的值最大为0.9
targetValue = 1.0f;
}
if (targetValue != loadingSlider.value)
{
loadingSlider.value = Mathf.MoveTowards(loadingSlider.value, targetValue, Time.deltaTime * loadingSpeed);
}
loadingText.text = ((int)(loadingSlider.value * 100)).ToString() + "%";
if ((int)loadingSlider.value == 1)
{
//允许异步加载完毕后自动切换场景
operation.allowSceneActivation = true;
}
}
}
在当前场景中使用SceneControl.LoadScene(string sceneName)静态方法就可以加载目标场景。