Unity3D异步加载场景的场景进度条的制作
01.菜鸟一些
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
/// <summary>
/// 加载游戏滑动条-使其平滑加载到100%并跳转到下一个场景
/// </summary>
public class LoadGame : MonoBehaviour {
public Slider processView;
// Use this for initialization
void Start () {
LoadGameMethod();
}
// Update is called once per frame
void Update () {
}
public void LoadGameMethod()
{
StartCoroutine(StartLoading_4(2));
}
private IEnumerator StartLoading_4(int scene)
{
int displayProgress = 0;//进程 displayProgress向toProgress靠拢
int toProgress = 0;//目标
//
//异步加载,并获取加载进度
//LoadSceneAsync(scene) 返回一个协程(当前进度)
AsyncOperation op = SceneManager.LoadSceneAsync(scene);
op.allowSceneActivation = false; //若设置为false 则会加载到0.89999999暂停
while (op.progress < 0.9f)
{
//op.progress当前进度是一个0~1的值
toProgress = (int)op.progress * 100;
while (displayProgress < toProgress)
{
++displayProgress;
SetLoadingPercentage(displayProgress);
//WaitForEndOfFrame等待所有的相机和UI等渲染完成
//因为进度条有变动,需要进行渲染
yield return new WaitForEndOfFrame();
}
}
toProgress = 100;
while (displayProgress < toProgress)
{
++displayProgress;
SetLoadingPercentage(displayProgress);
yield return new WaitForEndOfFrame();
}
op.allowSceneActivation = true;
}
private void SetLoadingPercentage(float v)
{
processView.value = v / 100;
}
方式2.简单一些
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/// <summary>
/// 异步加载进度条
/// </summary>
public class LoadingScene : MonoBehaviour
{
public Slider processBar;
private AsyncOperation async;
// 当前进度,控制滑动条的百分比
private uint nowprocess = 0;
void Start ()
{
// 开启一个协程
StartCoroutine (loadScene ());
}
// 定义一个协程
IEnumerator loadScene ()
{
//异步加载场景
async = Application.LoadLevelAsync ("场景名");
async.allowSceneActivation = false;
// 下载完成后返回async
yield return async;
}
void Update ()
{
// 判断是否加载完需要跳转的场景数据
if (async == null) //没有加载完成
{
return;
}
// 进度条需要到达的进度值
uint toProcess;
if (async.progress < 0.9f) {
// 进度值
toProcess = (uint)(async.progress * 100);
}
else { // 加载完毕
// 进度值为100
toProcess = 100;
}
// 如果滑动条的当前进度,小于当前加载场景的方法返回的进度
if (nowprocess < toProcess) {
// 当前滑动条的进度加一
nowprocess++;
}
// 设置滑动条的value
processBar.value = nowprocess / 100f;
//加载完毕
if (nowprocess == 100) {
// 设置为true的时候,如果场景数据加载完毕,就可以自动跳转场景
async.allowSceneActivation = true;
}
}
}