Unity场景的自动加载
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadingScene : MonoBehaviour {
/// <summary>
/// 滚动条
/// </summary>
public Slider slider;
/// <summary>
/// 显示滚动条当前的值(进度)
/// </summary>
public Text sliderValue;
void Start () {
LoadGame();
}
public void LoadGame()
{
StartCoroutine(StartLoading_Scene1(2));
}
/// <summary>
/// 自动加载 File中的BuildSeting中的第二个场景
/// </summary>
/// <param name="scene"></param>
/// <returns></returns>
private IEnumerator StartLoading_Scene1(int scene)
{
//当前滚动条上的值
float sliderValue = 0;
//已经加载的进度
float progressValue = 0;
//AsyncOperation op = Application.LoadLevelAsync(scene); //已弃用
//当加载达到100%的时候,跳转到指定的场景。
AsyncOperation op = SceneManager.LoadSceneAsync(scene);
//即使场景已经加载完成,也不会自动跳转,直到allowSceneActivation = true
op.allowSceneActivation = false;
//当AsyncOperation中获取资源的进度小于 90%的时候,也就是说progress可能是0.9的时候就直接进入新场景了
while (op.progress < 0.9f)
{
//当前资源的加载进度 赋值给 progressValue
progressValue = op.progress * 100;
//如果当前的sliderValue 的值小于 当前资源的加载进度的时候,sliderValue的值自加,直到等于progressValue的值
if (sliderValue < progressValue)
{
//sliderValue的值自加
++sliderValue;
//当前加载的值显示在Slider上的text中
SetLoadingPercentage(sliderValue);
yield return new WaitForEndOfFrame();
}
}
//当Progress的值大于 0.9的时候,progressValue = 100。
progressValue = 100;
while(sliderValue < progressValue)
{
++sliderValue;
SetLoadingPercentage(sliderValue);
yield return new WaitForEndOfFrame();
}
//然后把allowSceneActivation 的值置为true(即加载完场景资源之后自动进入到下一场景)。
op.allowSceneActivation = true;
}
/// <summary>
/// SliderBar上显示sliderValue的值
/// </summary>
/// <param name="progress"></param>
public void SetLoadingPercentage(float progress)
{
slider.value = progress / 100;
print(slider.value);
//print(progress);
sliderValue.text = progress.ToString();
}
}