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

Unity 切换场景

2018-01-26 16:52 453 查看

一、定义

void SceneManager.LoadScene(int sceneBuildIndex, SceneManagement.LoadSceneMode mode = LoadSceneMode.Single) :
void SceneManager.LoadScene(string sceneName, SceneManagement.LoadSceneMode mode = LoadSceneMode.Single)


通过在Build Settings中它们的名称或索引加载场景(注意那是不区分大小写)

指定场景名称可以是路径的最后部分不加.unity扩展名或者全部路径不加.unity扩展名。该路径在 Build Settings窗口中被精确的显示出来。如果场景名是指定的将会加载匹配到的首个场景。如果有多个名称相同但是路径不同的场景,你应该使用全部路径。

SceneManager sm = SceneManager.GetActiveScene(); //获取激活(当前)的场景
sm.buildIndex; //场景的编号
sm.name; //场景的名称


AsyncOperation SceneManager.LoadSceneAsync(string levelName)


你可以yield直到异步操作继续,或手动检查它是完成的(isDone)或是进度中(progress)。

AsyncOperation.isDone 操作是否完成(只读)

AsyncOperation.progress 操作的进度(只读)

AsyncOperation.priority 优先权,让你调整异步操作调用将被执行的顺序

二、代码实战

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

public class ChangeSceneLevel : MonoBehaviour {

private AsyncOperation mAsyncOperation;
private int progress = 0;
private int mCurProgress = 0;

void Start()
{
StartCoroutine(LoadScene());
}

private IEnumerator LoadScene()
{
// u3d 5.3之后使用using UnityEngine.SceneManagement;加载场景
mAsyncOperation = SceneManager.LoadSceneAsync("Example_01");
// 不允许加载完毕自动切换场景,因为有时候加载太快了就看不到加载进度条UI效果了
mAsyncOperation.allowSceneActivation = false;
// mAsyncOperation.progress测试只有0和0.9
while (!mAsyncOperation.isDone && mAsyncOperation.progress < 1)
{
yield return mAsyncOperation;
//不会调用到该位置
Debug.Log("Done");
}
}

void Update()
{
Debug.Log("u:" + mAsyncOperation.progress + ", " + mAsyncOperation.isDone + ", " + progress + ", " + mCurProgress);
//进度最多只能无限接近0.9(但是到不了0.9),然后场景激活成功后又会变为0
//isDone始终为false
if (mAsyncOperation.progress < 0.899) {
progress = (int)(mAsyncOperation.progress * 100);
} else {
progress = 100;
}
if (mCurProgress <= progress) {
mCurProgress++;
} else if (mCurProgress >= 100) {
// 必须等进度条跑到100%才允许切换到下一场景
mAsyncOperation.allowSceneActivation = true;
//切换场景之后上一个场景的代码就失效了,包括该代码
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  loadSceneAsync