官方的事件函数的执行顺序中有详解(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的值为枚举类型,详细的参数请参考官网>>