其他分享
首页 > 其他分享> > Unity场景:异步加载

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%";
	}

}

标签:异步,WaitForEndOfFrame,Img,Text,Percent,Unity,operation,加载,displayProcess
来源: https://blog.csdn.net/weixin_38531633/article/details/116896270