首先如下图把相关场景加入到Build Settings
Loading 脚本内容如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Loading : MonoBehaviour
{
public string SceneName;
private Text txt_Progress;
private AsyncOperation ao;
private bool isLoad = false;
private void Awake()
{
txt_Progress = GetComponent<Text>();
txt_Progress.text = "";
GameObject.Find("btn_Start").GetComponent<Button>().onClick.AddListener(() =>
{
StartLoad();
});
}
private void StartLoad()//开始加载
{
gameObject.SetActive(true);
StartCoroutine("Load");//开启加载协程,为什么有引号,因为必须有引号,协程才能关闭停止
}
IEnumerator Load()//协程加载
{
int displayProgress = -1;
int toProgress = 100;
while (displayProgress < toProgress)//加载过程中执行
{
++displayProgress;
ShowProgress(displayProgress);//显示加载进度
if (isLoad == false)
{
ao = SceneManager.LoadSceneAsync(SceneName);//异步加载,返回值是AsyncOperation,是异步进程
ao.allowSceneActivation = false;//是否允许场景激活,加载进度没有达到100,则一直显示加载场景
isLoad = true;//防止多次加载
}
yield return new WaitForEndOfFrame();//每执行一次While之后等待一下,等待这一帧的结束
}
if (displayProgress == 100)
{
ao.allowSceneActivation = true;//当被加载到100之后,激活被加载的场景
StopCoroutine("Load");//停止协程
}
}
private void ShowProgress(int progress)
{
txt_Progress.text = progress.ToString() + "%";
}
}
详细教程请见:http://www.sikiedu.com/course/306/task/16503/show