OnLevelWasLoaded廢棄

Unity 5.4的版本移除了OnLevelWasLoaded接口。
這個(gè)接口可以在MonoBehaviour Awake之后,在過場景的結(jié)束的時(shí)候被調(diào)用。
新版本提供SceneManager.sceneLoaded這個(gè)委托函數(shù)來做更靈活的調(diào)用。

為了和以前的邏輯一致一般我們會(huì)在Awake之后注冊這個(gè)委托函數(shù),然后再這個(gè)函數(shù)執(zhí)行結(jié)束之后取消注冊,當(dāng)對(duì)象的生命周期為只在當(dā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è)場景被加載之前就注冊這個(gè)函數(shù),可以通過RuntimeInitializeLoadType來做到

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ù)的注冊

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容