Unity 切换场景

一、定义

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;
            //切换场景之后上一个场景的代码就失效了,包括该代码
        }
    }
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值