場景的非同步載入(按鈕按下,開始載入)
阿新 • • 發佈:2018-11-19
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Loading : MonoBehaviour { //滑動條 public Slider LoadingSlider; //顯示進度文字 public Text LoadingText; private float loadingSpeed = 1; private float targetValue; //非同步操作協同程式 private AsyncOperation operation; private bool isLoading; void Start () { LoadingSlider.value = 0.0f; } public void LoadingMain() { StartCoroutine(AsyncLoading()); isLoading = true; } IEnumerator AsyncLoading() { operation = SceneManager.LoadSceneAsync("main"); //阻止當前載入完成自動切換 operation.allowSceneActivation = false; yield return operation; } void Update() { if (isLoading) { targetValue = operation.progress; //operation.progress非同步操作協同程式完成的程度,最大是1 if (operation.progress >= 0.9f) { targetValue = 1.0f; } if (targetValue != LoadingSlider.value) { //插值運算 LoadingSlider.value = Mathf.Lerp(LoadingSlider.value, targetValue, Time.deltaTime * loadingSpeed); //絕對值 if (Mathf.Abs(LoadingSlider.value - targetValue) < 0.01f) { LoadingSlider.value = targetValue; } } LoadingText.text = ((int)(LoadingSlider.value * 100)).ToString() + "%"; if ((int)(LoadingSlider.value * 100) == 100) { //允許非同步載入完畢後自動切換場景 operation.allowSceneActivation = true; } } } }