最近在做一个游戏项目,想在进入游戏开始场景之前添加一个加载场景,在加载场景中通过异步加载的方式跳转到游戏开始场景中。
- 首先在场景中创建一个Slider,根据自己的需求可以修改一下它的样式和对应颜色:
- 编写脚本LoadScene.cs,在该脚本中实现场景的异步加载:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
/// <summary>
/// 加载场景
/// </summary>
public class LoadScene : MonoBehaviour
{
/// <summary>
/// 滑动条
/// </summary>
private Slider slider;
/// <summary>
/// 当前进度值
/// </summary>
private int currentProgress=0;
/// <summary>
/// 目标进度
/// </summary>
private int targetProgress=0;
// Start is called before the first frame update
void Start()
{
//获取到Slider组件
slider = GameObject.Find("Slider").GetComponent<Slider>();
//开启协程
StartCoroutine(LoadingScens());
}
/// <summary>
/// 异步加载场景
/// </summary>
/// <returns>协程</returns>
private IEnumerator LoadingScens()
{
//异步加载1号场景
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync("MoveScene");
//不允许场景立即激活,
//异步加载进度在allowSceneActivation=false时,会卡在0.89999的一个值,这里乘100转整形
asyncOperation.allowSceneActivation = false;
//当异步加载小于0.9f的时候
while (asyncOperation.progress < 0.9f)
{
targetProgress = (int)(asyncOperation.progress * 100);
yield return LoadProcess();
}
//循环后,当前进度已经为90了,所以需要设置目标进度到100,继续循环
targetProgress = 100;
yield return LoadProcess();
//加载完毕,这里激活场景跳转场景成功
asyncOperation.allowSceneActivation = true;
}
/// <summary>
/// 等待帧
/// </summary>
/// <returns>等一帧</returns>
private IEnumerator<WaitForEndOfFrame> LoadProcess()
{
//当前进度<目标进度时
while (currentProgress < targetProgress)
{
//当前进度不断累加(如果场景很小,可以调整这里的值,例如:+=10,+=20,来调节加载速度)
++currentProgress;
//给UI进度条赋值
yield return new WaitForEndOfFrame();
slider.value = (float)currentProgress / 100;
}
}
}
- 给创建的Slider对象添加脚本LoadScene.cs
- 运行项目,观察实现的效果: