Unity3D实践系列04, 脚本的生命周期

Unity3D脚本生命周期是指从脚本的最初唤醒到脚本最终销毁的整个过程。生命周期的各个方法被封装到了MonoBehaviour类中。具体来说如下:

1、In Editor Mode 编辑模式

当在编辑器中把脚本绑定到某个GameObject的时候,调用了MonoBehaviour类的Reset方法。

2、Startup 开始运行阶段

 

如果脚本所绑定的GameObject是存在的,MonoBehaviour类的的Awake方法首先被调用。

随之执行MonoBehaviour类的OnEnable方法。

如果GameObject还未被运行,就调用MonoBehaviour类的Start方法。

3、Updates 经历每个帧阶段

 

即经过每个帧时的阶段。这里依次执行MonoBehaviour类的FixedUpdate方法、Update方法、LateUpdate方法,Update方法和LateUpdate方法在经历每帧的时候都会被执行,只不过LateUpdate方法的调用是在调用Update方法之后。FixedUpdate方法是每隔一段时间调用的方法,比如一个帧是60ms,如果FixedUpdate方法的fixed time step被设置成20ms,那么FixedUpdate方法会在这一帧被执行3次。

4、Rendering 渲染阶段

 

如果Scene中的GameObject被渲染了,且渲染对Camera是可见的,会调用MonoBehaviour类的OnWillRenderObject方法。

5、GUI 界面元素阶段

 

形成GUI元素时调用,执行MonoBehaviour类的OnGUI方法。通常至少被调用两次,一次有关layout的事件,一次有关repaint的事件。

6、Teardown 销毁阶段

 

在这个阶段,依次执行MonoBehaviour类的OnDisable方法和OnDestroy方法。OnDisable方法对GameObject禁用,OnDestroy方法用来真正销毁Scene中的GameObject。

在以上生命周期的6个阶段,通常会用到如上的6个方法:Awake, Start, FixedUpdate, Update, LateUpdate。

接着上一篇"Unity3D实践系列03,使用Visual Studio编写脚本与调试"的Unity项目。

点击"Hierarchy"窗口中的Camera。

在Camera的"Insepctor"窗口,鼠标移动至"Hello World(Script)"之上,右键,点击"Remove Component"。

在"Project"窗口下的"Assert"中的"_MyScripts"文件夹中,创建一个名称为"MyLifetime"的脚本。

双击"MyLifetime"在Visual Studio中打开,编辑如下:

using UnityEngine;
using System.Collections;
public class MyLifetime : MonoBehaviour {
    // Use this for initialization
    void Start () {
        Debug.Log("游戏开始~~");
    }
    void Awake()
    {
        Debug.Log("唤醒~~");
    }
    void FixedUpdate()
    {
        Debug.Log("FixedUpdate");
    }
    
    // Update is called once per frame
    void Update () {
        Debug.Log("Update");
    }
    void LateUpdate()
    {
        Debug.Log("LateUpdate");
    }
}

保存,把脚本绑定到"Hierarchy"窗口的Camera上,通过把"MyLifetime"脚本拖动到"Hierarchy"窗口的Camera上或Camera相关的"Inspector"窗口上。

运行,看到如下效果:

6

Awake方法和Start方法

 

可以看到,Awake方法总是在游戏开始之前被调用,无论脚本组件是否被激活都会被调用,一般用Awake方法来创建变量。而Start方法在所有Awake方法被执行之后、Update方法被调用之前被调用,而且只有脚本组件激活时才能被调用,一般用来给变量赋值。

也就是说,

如果Scene中的GameObject被禁用,Awake方法和Update方法都不会被调用。

如果脚本组件被禁用,AWake方法会被调用,Start方法不会被调用。

FixedUpdate方法和Update方法

 

Update方法在每一帧被调用一次,一般用于非物理运动;FixedUpdate方法每隔固定时间被调用一次,一般用于物理运动。一旦涉及到物理运算,比如Collide等,一般把方法写到FixedUpdate中。

修改如下MyLifetime类:

using UnityEngine;
using System.Collections;
public class MyLifetime : MonoBehaviour {
    // Use this for initialization
    void Start () {
        Debug.Log("游戏开始~~");
    }
    void Awake()
    {
        Debug.Log("唤醒~~");
    }
    void FixedUpdate()
    {
        Debug.Log("FixedUpdate time is" + Time.deltaTime);
    }
    
    // Update is called once per frame
    void Update () {
        Debug.Log("Update time is" + Time.deltaTime);
    }
    void LateUpdate()
    {
        Debug.Log("LateUpdate");
    }
}

可以看到,每次调用FixedUpdate方法所耗去的时间是相同的;而每次调用Update方法所耗去的时间是不同的。

7

另外,可以在"Edit"菜单,"Project Settings"下的"Time"中,修改"Fixed Timestep"项。

8

原文地址:https://www.cnblogs.com/darrenji/p/4588178.html