Unity3d中mono方法生命周期及执行顺序小结(一)

第一次写博客,如有不足之处,请在下方留言,谢谢。

Mono自带主要方法:Awake、OnEnable、Rest、Start、FixedUpdate、Update、LateUpdate、OnGUI、OnApplicationPause、OnApplicationQuit、OnDisable、OnDestroy

从Unity Manual中给出的Mono自带方法的生命周期结构图如下(分三块上传):
这里写图片描述
这里写图片描述
这里写图片描述
单个Mono方法执行如上图。
而多个Mono之间的方法的执行顺序呢?以前有看过不记得名的大神的Blog中有提到过,多个Mono之间的方法执行顺序是先统一执行Awake,然后依次下去。
但是其中Mono与Mono之间谁先谁后呢?为此我做了个小实验:
以下有2个Mono,3个go:

public class MonoA : MonoBehaviour
{

    void Awake()
    {
        Debug.Log("this is Awake of MonoA!" + gameObject.name);
    }
    void Start()
    {
        Debug.Log("this is Start of MonoA!" + gameObject.name);
    }

    bool isPrint = false;
    void Update()
    {
        if (!isPrint)
        {
            Debug.Log("this is Update of MonoA!" + gameObject.name);
            isPrint = true;
        }
    }
}
public class MonoB : MonoBehaviour
{

    void Awake()
    {
        Debug.Log("this is Awake of MonoB!" + gameObject.name);
    }
    void Start()
    {
        Debug.Log("this is Start of MonoB!" + gameObject.name);
    }

    bool isPrint = false;
    void Update()
    {
        if (!isPrint)
        {
            Debug.Log("this is Update of MonoB!"+gameObject.name);
            isPrint = true;
        }
    }
}

其中在Hierarchy中的顺序如下:
CubeA->MonoA,CubeB->MonoB,CubeC->MonoA,MonoB
goC上面悬挂了两个脚本,Inspector中情况如下
OK,一切准备就绪,Play……
得出运行结果如下:
这里写图片描述
由此不难得出,Mono中自带方法执行顺序,是自下至上的,Inspector中也是自下至上,与Hierarchy中的渲染顺序相反,在图层最上面的挂的脚本开始执行,在元素上最后的脚本先执行。

写在最后,一直在用Unity3d做开发,以前从来没有去深究过这些,最近受到一些触发,决心将以前一些知其然不知其所以然的知识重新梳理一遍,
希望有所进步,如果有朋友看到,有不当之处或有所不足之处,望能之处。
计划先过一遍Manual,然后过一遍UI源码,然后引擎源码。
所谓不积跬步无以至千里,以此共勉。

猜你喜欢

转载自blog.csdn.net/ppyy95239303/article/details/82531606