码迷,mamicode.com
首页 > 编程语言 > 详细

Unity3D脚本(MonoBehaviour)生命周期

时间:2016-04-18 09:52:35      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

场景中有2个物体:A,B
每一个物体上绑定2个脚本:A,B

初始化log:
Object : A , Script : B , Message : Awake
Object : A , Script : B , Message : OnEnable
Object : A , Script : A , Message : Awake
Object : A , Script : A , Message : OnEnable
Object : B , Script : B , Message : Awake
Object : B , Script : B , Message : OnEnable
Object : B , Script : A , Message : Awake
Object : B , Script : A , Message : OnEnable
Object : A , Script : B , Message : Start
Object : A , Script : A , Message : Start
Object : B , Script : B , Message : Start
Object : B , Script : A , Message : Start

特征:
1.每次Awake和OnEnable都是连续运行,最后才运行Start
2.物体运行顺序是依照字母升序排列。脚本顺序是依照字母降序排列
3.先运行完每一个物体上的全部脚本,再运行完下个物体上的全部脚本。以此类推。
相当于数据库的先group by obj ascending,group by script decending

销毁的log:
Object : A , Script : A , Message : OnDisable
Object : A , Script : B , Message : OnDisable
Object : A , Script : A , Message : OnDestroy
Object : A , Script : B , Message : OnDestroy
Object : B , Script : A , Message : OnDisable
Object : B , Script : B , Message : OnDisable
Object : B , Script : A , Message : OnDestroy
Object : B , Script : B , Message : OnDestroy
特征:
运行顺序:
1.依照唔拍拖的升序排列(ascending)
2.对于每一个物体上的脚本依照升序排列(ascending),这点是和初始化最大的不同点
3.先运行完一个物体上的全部脚本的disable,再运行该物体上的全部脚本的destroy。然后轮到下一个物体。

掌握脚本生命周期直接决定脚本之间的调用顺序,否则非常可能出现NPE(null pointer exception)
在android 出现NPE还好,一旦iOS出现NPE。就会出现BAD_ACCESS,程序就挂掉了。这点Mono框架做的不是非常出色。


附:
AbstractMonoBehaviour.cs
using UnityEngine;
using System.Text;
public abstract class AbstractMonoBehaviour : MonoBehaviour 
{


    protected abstract bool EnableLog { get;}


void Start () 
       {
        Log("Start");
}
    void Awake()
    {
        Log("Awake");
    }


    void OnDestroy()
    {
        Log("OnDestroy");
    }


    void OnDisable()
    {
        Log("OnDisable");
    }


    void OnEnable()
    {
        Log("OnEnable");
    }

    


    protected void Log(object obj)
    {
        if (EnableLog)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Object : ").Append(gameObject.name)
                .Append(" , Script : ").Append(GetType().Name)
                .Append(" , Message : ").Append(obj);
            Debug.Log(sb.ToString());
        }
    }


}

A.cs
using UnityEngine;
public class A : AbstractMonoBehaviour
{
    protected override bool EnableLog
    {
        get { return true; }
    }
}
B.cs
using UnityEngine;
public class B : AbstractMonoBehaviour
{
    protected override bool EnableLog
    {
        get { return true; }
    }
}


Unity3D脚本(MonoBehaviour)生命周期

标签:

原文地址:http://www.cnblogs.com/bhlsheji/p/5403140.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!