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 Loading场景异步加载代码实现
最新推荐文章于 2025-08-04 10:30:29 发布
本文档介绍了如何使用C#在Unity3D中实现场景的异步加载。通过`SceneManager.LoadSceneAsync`方法进行异步加载,并通过`Slider`和`Text`组件实时更新加载进度。在加载过程中,利用`WaitForEndOfFrame`确保进度条平滑显示。当加载进度达到0.9f时,等待剩余部分完成并激活新场景。

1万+

被折叠的 条评论
为什么被折叠?



