Unity场景加载进度条直接从0跳至100问题求助
Unity场景加载进度条直接跳100%无过渡的解决方法
问题原因
- 目标场景资源量过小,加载速度极快,
AsyncOperation.progress瞬间从0跳到0.9,后续激活场景后进度直接拉满,肉眼看不到中间过程。 - 代码直接将真实加载进度赋值给UI组件,没有做平滑过渡处理,即使有微小进度变化也会瞬间完成。
解决方案
1. 添加进度平滑插值
通过分离真实加载进度与UI显示进度,使用Mathf.Lerp实现平滑过渡,让进度条有自然的动画效果:
public void Loading(string sceneID) { screen.SetActive(true); StartCoroutine(LoadingAsync(sceneID)); } public IEnumerator LoadingAsync(string sceneID) { AsyncOperation operation = SceneManager.LoadSceneAsync(sceneID); operation.allowSceneActivation = false; float targetProgress = 0f; float currentProgress = 0f; const float smoothSpeed = 5f; // 控制平滑速度,数值越大过渡越快 while (!operation.isDone) { // 将原生进度转换为0-1的范围(原生进度到0.9即表示加载完成) targetProgress = Mathf.Clamp01(operation.progress / 0.9f); // 平滑插值当前显示进度到目标进度 currentProgress = Mathf.Lerp(currentProgress, targetProgress, Time.deltaTime * smoothSpeed); // 更新UI显示 float displayPercent = currentProgress * 100f; Debug.Log($"{displayPercent:F1}%"); loadingBar.value = displayPercent; loadingPer.text = $"{displayPercent:F1}%"; // 等待UI进度接近100%后再激活场景 if (operation.progress >= 0.9f && currentProgress >= 0.99f) { operation.allowSceneActivation = true; } yield return null; } }
2. 模拟加载(调试用)
如果场景确实太小导致加载过快,可以在加载完成后添加短暂过渡或延迟,方便调试进度条效果:
// 修改operation.progress >=0.9的判断逻辑 if (operation.progress >= 0.9f) { // 先让UI进度平滑到100% while (currentProgress < 0.99f) { currentProgress = Mathf.Lerp(currentProgress, 1f, Time.deltaTime * smoothSpeed); float displayPercent = currentProgress * 100f; loadingBar.value = displayPercent; loadingPer.text = $"{displayPercent:F1}%"; yield return null; } // 可选:添加0.5秒延迟,让用户看到完整的进度条动画 yield return new WaitForSeconds(0.5f); operation.allowSceneActivation = true; }
3. 优化协程启动逻辑
去掉协程开头的yield return null,让加载逻辑立即执行,避免不必要的延迟:
// 原代码中的yield return null可以删除 public IEnumerator LoadingAsync(string sceneID) { // 移除yield return null,直接初始化加载操作 AsyncOperation operation = SceneManager.LoadSceneAsync(sceneID); // ... 后续代码不变 }
内容的提问来源于stack exchange,提问作者Felipe Hernández Bescós
相关产品推荐
相关产品推荐

