思路:
UI设计,异步加载主场景
由于主场景比较大,使用异步加载游戏主场景,如果想了解同步加载和异步加载,可以搜索其他博客加以了解,这里不再做更多解释
UI设计
添加一个slider作为进度条
异步加载主场景
添加脚本LoadingScene,编辑脚本
public class LoadingScene : MonoBehaviour {
public UISlider slider; //进度条
public UILabel label; //进度数
private AsyncOperation asyncOp;
private int nowprocess = 0; //目前的进度数
void Start()
{
StartCoroutine(StartLoading());
}
void Update()
{
if (asyncOp == null) //如果为空,则return,不运行下面的代码
{
return;
}
int toprocess; //要到达的进度数(最多只能到达90)
if (asyncOp.progress < 0.9f)
{
toprocess = (int)(asyncOp.progress * 100);
}
else //asyncOp.progress已经达到0.9,场景不会再加载,我们要手动加载剩余的10%
{
toprocess = 100;
}
if (nowprocess < toprocess)
{
nowprocess++; // nowprocess++可以使进度数从1逐步加载100,而不会跳跃性的加
}
slider.value = nowprocess / 100f; //更新进度条和进度数
label.text = (slider.value * 100).ToString()+"%";
if (nowprocess == 100) //加载完毕
{
asyncOp.allowSceneActivation = true;
}
}
//携程异步加载下个场景
private IEnumerator StartLoading()
{
asyncOp = Application.LoadLevelAsync(3);
asyncOp.allowSceneActivation = false; //AsyncOperation.isDone为false,AsyncOperation.progress的值增加到0.9后就保持不变
yield return asyncOp;
}
}