您的位置:首页 > 移动开发 > Unity3D

C# Unity3D Loading场景异步加载代码实现

2018-01-17 14:15 447 查看
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//引入命名空间
using UnityEngine.SceneManagement;
using UnityEngine.UI;

/// <summary>
/// 异步加载场景管理类
/// </summary>
public class LoadingManager : MonoBehaviour
{
/// <summary>
/// 进度条
/// </summary>
public Slider progressUI;

/// <summary>
/// 百分比描述文本
/// </summary>
public Text progressValue;

/// <summary>
/// 异步操作类
/// </summary>
private AsyncOperation prog;

void Start()
{
//启动协同
StartCoroutine(LoadAsycLevel());
}

/// <summary>
/// 设置进度条值
/// </summary>
/// <param name="value"></param>
private void SetProgressValue(int value)
{
progressUI.value = value;
progressValue.text = "当前加载进度" + value + "%";
}

/// <summary>
/// 异步加载场景
/// </summary>
IEnumerator LoadAsycLevel()
{
//异步加载场景
prog = SceneManager.LoadSceneAsync("Game");
//如果加载完成,也不进入场景
prog.allowSceneActivation = false;

//最终的进度
int toProgress = 0;

//显示的进度
int showProgress = 0;

//测试了一下,进度最大就是0.9
while (prog.progress < 0.9f)
{
//toProcess具有随机性
toProgress = (int)(prog.progress * 100);
Debug.Log((int)(prog.progress * 100));
while (showProgress < toProgress)
{
showProgress++;
SetProgressValue(showProgress);
Debug.Log(string.Format("1-------toProgress={0},showProgress={1}", toProgress, showProgress));
yield return new WaitForEndOfFrame(); //等待一帧
}
}
//计算0.9---1   其实0.9就是加载好了,我估计真正进入到场景是1
toProgress = 100;

while (showProgress < toProgress)
{
showProgress++;
SetProgressValue(showProgress);
Debug.Log(string.Format("2-------toProgress={0},showProgress={1}", toProgress, showProgress));
yield return new WaitForEndOfFrame(); //等待一帧
}

prog.allowSceneActivation = true;  //如果加载完成,可以进入场景
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# Unity3D 异步加载