轉載自:http://blog.csdn.net/chy555chy/article https://blog.csdn.net/chy555chy/article/details/79174405
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; //場景的名稱
SceneManager sm = SceneManager.GetActiveScene(); //獲取激活(當前)的場景 sm.buildIndex; //場景的編號 sm.name; //場景的名稱
你可以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;
//切換場景之後上一個場景的代碼就失效了,包括該代碼
}
}
}
此外,在切換場景時不摧毀某物體的方法爲:DontDestroyOnLoad();(運行一次次代碼後,此物體在本次程序運行不再摧毀)