场景中进度条加载
1.在Build Settings里添加两个场景,一个是进度条加载的场景,一个是加载完成后要跳转的场景。
2.在场景中添加Image和Text,作为进度条填充量和值。
3.相关代码:(赋给任意物体即可)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Load : MonoBehaviour {
private AsyncOperation aync;
public Image load; //进度条
private int figure = 0; //已加载的进度
public Text loadtext; //百分制显示进度数值
// Use this for initialization
void Start () {
//开启一个协程,它会根据迭代器中yield return 来判断什么时候暂时退出当前函数
//然后在下一段时间继续执行yield return 后面的函数代码
//会在第一次运行后一直执行,直到有代码控制它停止
StartCoroutine("LoadScence");
}
IEnumerator LoadScence() //定义一个迭代器,每一帧返回一次当前的载入进度,同时关闭自动的场景跳转
{
aync = SceneManager.LoadSceneAsync("shoot"); //要跳转的场景
aync.allowSceneActivation = false;
yield return aync;
}
// Update is called once per frame
void Update () {
if (aync == null) //判断是否有场景正在加载
{
return;
}
int progrssvalue = 0; //百分制进度
//当场景加载进度在90%以下时,将数值以整数百分制呈现,当资源加载到90%时就将百分制进度设置为100
if (aync.progress < 0.9f)
{
progrssvalue = (int)aync.progress * 100;
}
else
{
progrssvalue = 100;
}
//对进度条和百分制数据进行更改,已加载进度与百分制进度比较
if (figure < progrssvalue)
{
figure++;
load.fillAmount = figure / 100f; //进度条与已加载进度数值保持一致
loadtext.text = "加载资源中:" +figure.ToString() + "%";
}
//一旦进度到达100时,开启自动场景跳转,LoadSceneAsync会加载完剩下的10%的场景资源
//LoadSceneAsync只能加载90%的场景资源,剩下的10%场景资源要在开启自动场景跳转后才加载
if (figure == 100)
{
aync.allowSceneActivation = true;
}
}
}