Unity 5.4的版本移除了OnLevelWasLoaded接口。
這個(gè)接口可以在MonoBehaviour Awake之后吏口,在過(guò)場(chǎng)景的結(jié)束的時(shí)候被調(diào)用。
新版本提供SceneManager.sceneLoaded這個(gè)委托函數(shù)來(lái)做更靈活的調(diào)用。
為了和以前的邏輯一致一般我們會(huì)在Awake之后注冊(cè)這個(gè)委托函數(shù),然后再這個(gè)函數(shù)執(zhí)行結(jié)束之后取消注冊(cè)直秆,當(dāng)對(duì)象的生命周期為只在當(dāng)前場(chǎng)景的時(shí)候。
using UnityEngine;
using UnityEngine.SceneManagement;
class MyClass : MonoBehaviour {
void Awake() {
// do somethings
SceneManager.sceneLoaded += OnSceneLoaded;
}
void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, LoadSceneMode mode) {
// do things after scene loaded.
// Remove the delegate when no need.
SceneManager.sceneLoaded -= OnSceneLoaded;
}
}
如果我們想在第一個(gè)場(chǎng)景被加載之前就注冊(cè)這個(gè)函數(shù)鞭盟,可以通過(guò)RuntimeInitializeLoadType來(lái)做到
using UnityEngine;
using UnityEngine.SceneManagement;
class MyClass : MonoBehaviour {
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void OnRuntimeMethodLoad() {
// Add the delegate to be called when the scene is loaded, between Awake and Start.
SceneManager.sceneLoaded += SceneLoaded;
}
static void SceneLoaded(Scene scene, LoadSceneMode loadSceneMode) {
Debug.Log(System.String.Format("Scene{0} has been loaded ({1})", scene.name, loadSceneMode.ToString()));
}
void OnDestroy() {
// Remove the delegate when the object is destroyed
SceneManager.sceneLoaded -= SceneLoaded;
}
}
新接口需要我們更加妥善的管理新版本委托函數(shù)的注冊(cè)