官方的事件函數的執行順序中有詳解(Link:Execution Order of Event Functions)
(圖片來源:http://whatiseeinit.blogspot.com/2012/10/unity3d-monobehaviour-lifecycle.html)
通過實際操作來測試上述的流程:
1、新建一個場景:LifecycleTest
2、在同級目錄下新建一個C#腳本:LifecycleTest.cs,代碼如下:
using System; using UnityEngine; [ExecuteInEditMode] public class LifecycleTest : MonoBehaviour { private void Awake() { Debug.Log("Awake" + DateTime.Now.ToString()); } private void Reset() { Debug.Log("Reset" + DateTime.Now.ToString()); } private void OnEnable() { Debug.Log("OnEnable" + DateTime.Now.ToString()); } private void OnDisable() { Debug.Log("OnDisable" + DateTime.Now.ToString()); } private void OnDestroy() { Debug.Log("OnDestroy" + DateTime.Now.ToString()); } // Use this for initialization void Start () { Debug.Log("Start" + DateTime.Now.ToString()); } // Update is called once per frame void Update () { Debug.Log("Update" + DateTime.Now.ToString()); } }
3、將LifecycleTest.cs腳本拖拽至LifecycleTest場景的主相機(Main Camera)上(或者選中主相機,在檢視圖 — Inspector 中最底部按鈕 Add Component,輸入“LifecycleTest”然后回車,將選中的腳本附加到主相機中);
4、此時,控制台上將能看到相應的輸出
Awake –> OnEnable –> Reset –> Start –> Update
當場景卸載時(比如雙擊切換到另一個場景時,當前場景會被卸載 – unload),此時會觸發:
OnDisable –> OnDestroy
當場景被載入時(load)
Awake –> OnEnable –> Start –> Update
當C#腳本被修改時(Modified)時
OnDisable –> OnEnable
我們會發現上面有二對相對應的函數:
Awake —— OnDestroy
OnEnable —— OnDisable
卸載時是 OnDisable –> OnDestroy,加載時是 Awake –> OnEnable。
注意動態創建的實例對象,記得顯示設置隱藏標記(HideFlags)以便更加准確控制其生命周期,避免報錯或其它意外的發生。
using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { // Creates a material that is explicitly created & destroyed by the component. // Resources.UnloadUnusedAssets will not unload it, and it will not be editable by the inspector. private Material ownedMaterial; void OnEnable() { ownedMaterial = new Material(Shader.Find("Diffuse")); ownedMaterial.hideFlags = HideFlags.HideAndDontSave; GetComponent<Renderer>().sharedMaterial = ownedMaterial; } // Objects created as hide and don't save must be explicitly destroyed by the owner of the object. void OnDisable() { DestroyImmediate(ownedMaterial); } }
HideFlags的值為枚舉類型,詳細的參數請參考官網>>