您的位置:首页 > 移动开发 > Unity3D

基于Unity3D的异步加载场景的实现

2017-11-05 22:34 387 查看
在游戏中,异步加载场景是个特别有用的切换场景方式,尤其是对于资源比较大得场景。今天,我们就来实现一个异步加载场景功能。

1.打开Unity,创建俩个新场景,并添加到Build Setting中,如图:


2.打开StartScene场景,创建一个Slider控件,创建一个新的C#脚本:AsyncLoadScene.cs,并挂在Slider游戏对象上,并将SceneName赋值为AsyncScene,如图:


AsyncLoadScene脚本如下:

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

public class AsyncLoadScene : MonoBehaviour {
//异步加载的场景名字
public string sceneName;

//进度条
private Slider slider;
//异步操作
private AsyncOperation async;
//加载的进度
private int currentProcess;
private int totalProcess=0;

void Start(){
slider = GetComponent ();
StartCoroutine(Loading());
}
void Update()
{
if (async != null)
{
//注意async.progress最大返回值为0.9
if (async.progress < 0.85f) {
totalProcess = (int)(async.progress * 100);
} else {
totalProcess = 100;
}
if (currentProcess < totalProcess) {
currentProcess++;
}
slider.value = currentProcess/100f;
if (currentProcess == 100)
{
async.allowSceneActivation = true;
}
}
}
//进度加载
IEnumerator Loading()
{
async = SceneManager.LoadSceneAsync(sceneName);
async.allowSceneActivation = false;
yield return async;
}
}

3.点击运行,即可看到当Slider加载满时,切换到AsyncScene场景了。




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: