Unity场景:异步加载

示例代码

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Panel_Loading : MonoBehaviour
{
	Image Img_Load;
	Text Text_Percent;

	/// <summary>
	/// 虚拟进度
	/// </summary>
	private int _displayProcess;

	/// <summary>
	/// 当前进度
	/// </summary>
	private int _currentProcess;
	
	void Awake()
	{
		UpdateUI();
		Init();
	}
	
	void Init()
	{
		Img_Load = transform.Find_T<Image>("Img_LoadingBar");
		Text_Percent = transform.Find_T<Text>("Text_LoadingPercent");

		StartCoroutine("LoadScene");
	}

	IEnumerator LoadScene()
	{
		//状态重置
		_displayProcess = 0;

		//降低GC开销
		WaitForEndOfFrame WaitForEndOfFrame_ = new WaitForEndOfFrame();
		//发送的消息 data=K+V
		//必须要等一帧 不然加载界面刷不出来
		yield return WaitForEndOfFrame_;

		//开始异步加载
		AsyncOperation operation = SceneManager.LoadSceneAsync(Scene_Mgr.Instance.SceneName, LoadSceneMode.Single);
		operation.allowSceneActivation = false;

		while (operation.progress < 0.9f)
		{
			_currentProcess = (int)(operation.progress * 100);
			while (_displayProcess < _currentProcess)
			{
				_displayProcess += 1;
                Img_Load.fillAmount = _displayProcess / 100f;
                Text_Percent.text = _displayProcess.ToString() + "%";
                yield return WaitForEndOfFrame_;
			}

			yield return WaitForEndOfFrame_;
		}

		_currentProcess = 100;
		while (_displayProcess < _currentProcess)
		{
			_displayProcess += 1;
			Img_Load.fillAmount = _displayProcess / 100f;
			Text_Percent.text = _displayProcess.ToString() + "%";
			yield return WaitForEndOfFrame_;
		}
		operation.allowSceneActivation = true;
		yield return WaitForEndOfFrame_;
	}

	void UpdateUI()
	{
		Img_Load.fillAmount = 0;
		Text_Percent.text = "0%";
	}

}
上一篇:ArcGIS Server&ArcGIS API for JS之GenerateRenderer


下一篇:设计模式之工厂模式