Unity异步加载场景与加载进度条

异步加载场景分为A、B、C三个场景

A场景是开始场景;B场景是加载场景(进度条加载显示);C场景是目标场景

在A场景中添加一个按钮,触发函数:

//异步加载新场景
public void LoadNewScene()
{
	//保存需要加载的目标场景
	Globe.nextSceneName = "Scene";

	SceneManager.LoadScene("Loading");		
}


在B场景中添加一个脚本,挂载到Camera下

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

public class Globe
{
	public static string nextSceneName;
}

public class AsyncLoadScene : MonoBehaviour
{
	public Slider loadingSlider;

	public Text loadingText;

	private float loadingSpeed = 1;

	private float targetValue;

	private AsyncOperation operation;

	// Use this for initialization
	void Start ()
	{
		loadingSlider.value = 0.0f;

		if (SceneManager.GetActiveScene().name == "Loading")
		{
			//启动协程
			StartCoroutine(AsyncLoading());
		}
	}

	IEnumerator AsyncLoading()
	{
		operation = SceneManager.LoadSceneAsync(Globe.nextSceneName);
		//阻止当加载完成自动切换
		operation.allowSceneActivation = false;

		yield return operation;
	}
	
	// Update is called once per frame
	void Update ()
	{
		targetValue = operation.progress;

		if (operation.progress >= 0.9f)
		{
			//operation.progress的值最大为0.9
			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;
		}
	}
}


这里需要注意的是使用AsyncOperation.allowSceneActivation属性来对异步加载的场景进行控制

为true时,异步加载完毕后将自动切换到C场景

最后附上效果图



个人网站:www.liujunliang.com.cn

博客地址:blog.liujunliang.com.cn

本人也在寻找一份游戏开发实习工作,如果大佬们需要开发人员,请把我带走

这是我的简历:resume.liujunliang.com.cn/resume.pdf

作品的话可以私聊我哦!


你可能感兴趣的:(移动游戏开发,unity3d,Unity游戏开发)