Unity异步加载场景
程序员文章站
2022-04-03 12:28:57
...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Loading : MonoBehaviour
{
public Slider progressSlider; // 进度条Slider组件
public Text progressTex; // 显示进度的Text组件
private float loadingSpeed = 1;
private float targetValue;
private AsyncOperation operation;
private bool isInitSucceed = false;
void Start()
{
progressSlider.value = 0f;
progressTex.text = "0%";
string targetScene = "GameScene";
if (string.IsNullOrEmpty(targetScene))
{
Debug.LogError("TargetScene is Empty!");
return;
}
StartCoroutine(AsyncLoading(targetScene));
isInitSucceed = true;
}
void Update()
{
if (!isInitSucceed)
return;
targetValue = operation.progress;
if (operation.progress >= 0.9f)
{
targetValue = 1f;
}
if (targetValue != progressSlider.value)
{
progressSlider.value = Mathf.Lerp(progressSlider.value, targetValue, loadingSpeed * Time.deltaTime);
if (Mathf.Abs(progressSlider.value - targetValue) < 0.005f)
{
progressSlider.value = targetValue;
}
}
progressTex.text = (int) (progressSlider.value * 100) + "%";
if ((int) (progressSlider.value * 100) >= 100)
{
operation.allowSceneActivation = true;
isInitSucceed = false;
}
}
IEnumerator AsyncLoading(string targetScene)
{
operation = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(targetScene);
operation.allowSceneActivation = false;
yield return operation;
}
}
上一篇: 序列化问题