Detailed explanation of life cycle functions in Unity

Preface

In Unity, there is a particularly important knowledge point, the life cycle function. These things are all defined by the system and automatically called at runtime, but they need to inherit the MonoBehaviour class to use them . This class is automatically inherited from scripts created in Unity. It is precisely because of inheriting the MonoBehaviour class that Unity can call our script code in sequence to execute game logic.

Front row reminder: This article only represents my personal views for communication and learning. If you have any different opinions, please leave a comment. The author must study hard and make progress every day.

Video explanation:
Detailed explanation of Unity’s life cycle function_BiLiBiLi

1. Commonly used life cycle functions

1.What is life cycle

In Unity, scripts can be understood as instruction codes attached to game objects that define the behavior of game objects. A script must be bound to a game object before it can be called and start its life cycle. For example, when a bullet is generated when the left mouse button is pressed, the script attached to this game object begins its life cycle, and its life cycle does not end until it is destroyed when a certain logic is triggered. During this period, periodic functions such as Awake, Start, OnDestroy, etc. may be called in sequence, or functions such as Update, FixedUpdate, etc. may be executed in a loop, and one or more execution lines run through the life cycle of this script.

2.Reset() + example

This function will be called when the user first adds the component or clicks the Reset button, and will only take effect in the editor. It can be used to generate and modify editor nodes in large batches. You may not understand this. Here is an example.

If we have a map and need to add a large number of trees (here replaced by cylinders), these trees need to form a specific pattern and be named according to certain rules. At this time, the brush will not be able to do the job. Maybe it can be dynamically modified through code when the program is running. , but once the program ends, these trees will be destroyed again, and it will consume a lot of program running resources. At this time, through the Reset function, this requirement can be completed directly in the editor stage.

Create an empty node "Reset" in the editor and assign the script "Reset_Test.cs" to this empty node. The code and running results are as follows
Insert image description here

It should be noted that all initialization operations should be completed in Reset, because it only calls the Reset function and will not call functions such as Start, because this is done in the editor and the program has not yet been run.


    public int row = 3;
    public int col = 9;
    private void Reset()
    {
        GameObject t = null;
        GameObject tree = GameObject.Find("Cylinder");
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                Vector3 position = new Vector3(i * 2, 0, j * 2);
                t = Instantiate(tree, position, Quaternion.identity);
                t.transform.SetParent(transform, false);
                t.gameObject.name = "tree:" + i + "," + j;
            }

        }
    }

3. Brief introduction to commonly used periodic functions

Awake()

This function is called when the script instance is loaded and is only called once

OnEnable()

Called once when the script is enabled, only listens to respond to this function when the game object is disabled

Start()

Called after Awake and before Update, only called once

FixedUpdate()

Physics update function, executed in a loop, once every 0.02 seconds (not affected by the FPS frame rate, the time can be changed), all physics-related updates should be processed in this function

Update()

Update function, executed once per frame, affected by FPS frame rate

LateUpdate()

Update function later, called after all Updates are executed, the frame interval is the same as Update

onGUI()

Called when rendering and handling GUI events, executed every frame

OnDisable()

Called once when the script is disabled, and repeatedly called OnDisable and OnEable when the script is repeatedly disabled or enabled.

OnDestroy()

Called when the script is destroyed, it will only be called on the activated object


2. Differences and demonstrations

1.The difference between Awake and Start

(1). Test an object to mount four scripts. The running screenshot and code are as follows

Insert image description here

//AwakeAndStart.cs
    private void Awake() {
        Debug.Log("Awake1");
    }
    private void Start() {
        Debug.Log("Start1");
    }
//AwakeAndStart1.cs
    private void Awake() {
        Debug.Log("Awake2");
    }
    private void Start() {
        Debug.Log("Start2");
    }
//AwakeAndStart2.cs
    private void Awake() {
        Debug.Log("Awake3");
    }
    private void Start() {
        Debug.Log("Start3");
    }
//AwakeAndStart3.cs
    private void Awake() {
        Debug.Log("Awake4");
    }
    private void Start() {
        Debug.Log("Start4");
    }
(2). Test four objects and mount four scripts. The running screenshots and codes are as follows

(Contrast the order of mounting, the script code has not been changed)
Insert image description here

Look at the result... It seems that Awake is executed in reverse order, and Start is out of order. However, after executing it multiple times, the result is still the same. The confirmed result is that Start is executed only after Awake is executed. It is difficult for the author to sort out this order due to my limited ability . If you need to create the object in one script and obtain the object in another script, but cannot control the execution order between the scripts, it is recommended to use Awake to create the game object and Start to obtain the object, so as to ensure that no null pointer errors are reported.

2.The difference between FixedUpdate\Update\LateUpdate

These functions are all frame execution functions, but the execution time is different. The following figure illustrates the frame interval time and execution order of these functions.
Insert image description here

As can be seen from the figure, FixedUpdate is executed first, Update and LateUpdate are executed in sequence. In terms of frame interval, FixedUpdate is always executed once every 0.02 seconds, while Update and LateUpdate are executed at the same frame interval. Sometimes, FixedUpdate is executed multiple times. Update and LateUpdate are executed only once.
Everyone knows that physics-related operations should be placed in FixedUpdate. It is precisely because the Update execution time is not fixed, which will cause a stuck delay effect, so it is placed in FixedUpdate.
FixedUpdate fixed time can be modified, Edit->Project Setting->time->Fixed timestep.

//这里Update是靠前的,所以代码执行顺序和代码书写顺序是无关的
    private void Update() {
        Debug.Log("Update:" + Time.deltaTime);
    }
    private void LateUpdate() {
        Debug.Log("LateUpdate:" + Time.deltaTime);
    }
    private void FixedUpdate() {
        Debug.Log("FixedUpdate:" + Time.deltaTime);
    }

3. Demonstration of disabling, enabling and destroying game objects

(1). When the game object is disabled or enabled, the mounted periodic function is demonstrated as follows

Insert image description here

You can intuitively see from the animation demonstration that when the object is disabled, Awake and Start are not executed. When the object is disabled and enabled multiple times, its Awake and Start are only executed once, while OnEnable and OnDisable are will be called multiple times. When the program exits, if the object is enabled, the program will first disable it and then destroy it.

//OnOff.cs
    private void Awake() {
        Debug.Log("Awake执行");
    }
    private void Start() {
        Debug.Log("Start执行");
    }
    private void OnEnable() {
        Debug.Log("OnEnable执行");
    }
    private void OnDisable() {
        Debug.Log("OnDisable执行");
    }
    private void OnDestroy() {
        Debug.Log("OnDestroy执行");
    }
(2). When the game object is destroyed, the demonstration is as follows

Insert image description here

Here I pressed the D key. After it monitored it, it first executed OnDisable and then executed Destroy.

When the game object is disabled (disabled from the beginning to the end), Destroy will not be monitored.
If it is disabled at the beginning and then unlocked and disabled again, or it is not disabled at the beginning and is disabled after running, Destroy will still be monitored.

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.D))
            Destroy(this.gameObject);
    }
    private void OnEnable()
    {
        Debug.Log("OnEnable执行");
    }
    private void OnDisable()
    {
        Debug.Log("OnDisable执行");
    }
    private void OnDestroy()
    {
        Debug.Log("OnDestroy执行");
    }

3. Execution process example diagram

Insert image description here

I drew the picture myself, please criticize and correct me if there is anything wrong.


4. Summary and reference materials

1. Summary

I don’t know much about OnGUI. I didn’t mention it this time. I will modify and supplement it in the future.
Awake is generally used to initialize the object creation operation, and then use Start to obtain it, which can ensure the sequential execution under absolute control.
FixedUpdate is used for physical operations to ensure the frame interval time. Same, the operation is smooth
FixedUpdate-Update-LateUpdate loop execution, but the frequency of FixedUpdate may be higher or lower.
When manual destruction or the parent object is destroyed, Destroy is called, but OnDisable is called first.

2.Reference materials

1.https://www.jianshu.com/p/32ce8768607f
2.https://blog.csdn.net/qq_42351033/article/details/83047657
3.https://www.xuanyusong.com/archives/2378
4.https://blog.csdn.net/Marine_snow/article/details/117127889
5.https://blog.csdn.net/REIONE/article/details/52400015
6.https://www.jianshu.com/p/27190f23a01b

Guess you like

Origin blog.csdn.net/weixin_43147385/article/details/123928964