[Unity] Unity life cycle


When studying the life cycle, I found that there are two official versions of the life cycle. The old version seems to be before 5.0, and the new version is after 5.0. I translated and organized it myself, and drew two pictures. I hope it will be helpful to everyone.
**Note:** The picture is drawn with Astah, if you want the original version, you can private message me.

Legacy Unity Lifecycle

- Official Legacy Lifecycle

insert image description here

- Personally organize the translated version

insert image description here

The new version of Unity life cycle

- Official new version life cycle

insert image description here

- Personally organize the translated version

insert image description here


life cycle function

1. Initialization phase

Awake

Awake is called when a script instance is loaded. Regardless of whether the script is available or not, it will be called as long as the object is loaded. Awake is often used to initialize variables or game states before the game starts. It can be judged that the script is executed when the conditions are met (only call once ).

OnEnable (when available)

This function is called when the object becomes available or activated. ( can be called multiple times ).

Reset (Editor)

Reset is called when the user clicks the Reset button of the inspector or when the component is added for the first time. This function is only called in edit mode. Reset is most commonly used to give a most commonly used default value in the inspector.

Start

Called once when the object is loaded and the script object is enabled, often used for data or logic object initialization ( only called once ).
Start is called only before the Update function is called for the first time, and only once when the script instance is enabled.
Awake is always executed before Start. The lazy initialization code can be adjusted as needed.

2. Physical stage

FixedUpdate (fixed update)

FixedUpdate is called based on a reliable timer, independent of frame rate. If the fixed time step is smaller than the actual frame update time, then the physics loop may occur more than once per frame. When dealing with the physical properties of objects (Rigidbody, Force, Collider) or input events, you need to use FixedUpdate instead of Update to make the physical performance of the object smoother. In fact, FixedUpdate is not really executed according to the real time interval, but is executed according to the Timer time interval, but the Timer is not the real time in the true sense, its function is to create a time in the operating environment that is highly similar to the real time variables to achieve logical stabilization of the physical frame. Because of this characteristic of FixedUpdate, it is strongly recommended to only do physical-related processing in this step, and do not put other types of processing (such as network frame synchronization) into this step. The default frequency is about 0.02s, which can be modified manually.

operations during

After the fixed update is over, a series of operations will be performed inside the system. The most important thing is Unity's internal physical update, which is the real physical update operation.
The specific execution steps are roughly as follows:
insert image description here

OnTriggerXXX (trigger)

Invoked when the trigger is fired.

OnCollisionXXX (collision)

Called when a collision event occurs.

yield WaitForFixedUpdate (coroutine: end of physical frame)

When the physical frame is executed, it will jump to this coroutine. The call of the coroutine is different from the method. It can be understood as setting a stuck point in a piece of code. When the program executes to the timing that matches the stuck point, the stuck point The following code will continue to execute.

public class Test : MonoBehaviour
{
    
    
    void Awake()
    {
    
    
        Debug.Log("0");
        StartCoroutine(TestCoroutine());
        Debug.Log("2");
    }

    void FixedUpdate()
    {
    
    
        Debug.Log("3 - FixedUpdate");
    }

    IEnumerator TestCoroutine()
    {
    
    
        Debug.Log("1");
        yield return new WaitForFixedUpdate();
        Debug.Log("4");                      // 当物理帧结束(触发WaitForFixedUpdate)后才会执行这条语句。 
    }
}

Physical Phase Summary

The occurrence of this stage has nothing to do with rendering. Its characteristics determine its function of processing physical events, making the physical display effect smoother. In addition, the frequency of fixed updates is not really fixed. The actual execution will be biased according to the CPU rotation time slice. shift, but this shift can basically be ignored.

3. Input event stage

Various input events such as mouse, keyboard, touch screen, and joystick will be triggered at this stage. At this point in time, the physical update has been executed (if physical update is required), but the logical update and rendering have not been executed. To understand the timing of this trigger, In order to better grasp the code logic.

4. Game logic stage

Update

Update is actually called every frame. Due to the difference in system performance and game size, the refresh rate of each frame is also different, so don't expect too much to complete the task on time in the Update method.
Update and FixedUpdate actually use the same thread. The processing method of update in the loop is to judge whether to perform the next update according to the offset time from the previous frame to the present after the update is completed. The essence of Update is the callback function. As long as it is a callback function, there is a loss of context transfer, so if you want to reduce callbacks, you can consider implementing an update mechanism yourself and use virtual functions instead of update . For specific content, you can read another article: [Unity] Advanced Unity Development (2) Custom Update .

Judge multiple coroutine points

In the yield WaitForFixedUpdate chapter, we have already talked about the execution order of the coroutines. After the Update is executed, the trigger points of the following coroutines will be reached. If the relevant coroutines are set before then, it will take effect at this time.

  • yield null
  • yield WaitForSeconds
  • yield WWW: This is more important . When the network task is completed, the operation after WWW will be executed at this time point of the current frame. Generally used to load resources asynchronously.
  • yield StartCoroutine

Internal animation update

After several coroutines, Unity will carry out the second large-scale system internal operation. The main work content is to update the animation. The specific content is as follows:
insert image description here

LateUpdate (late update)

This method will be called after the Update method is called every frame. Because there is often a secondary calculation in the game development process, such as the protagonist moves, the camera moves with it. If the camera is also following when the protagonist is moving, when there is a phase between the object and the player, there may be twitching and shaking (because the follow is not called after the logic of this frame is completely over). So the emergence of LateUpdate can make the program smoother.

5. Rendering stage

OnWillRenderObject

Called when an object is about to be rendered.

OnPreCull

This function is only used in scripts hosted by cameras. Triggered when this camera culls a rendered scene.

OnBecameVisable (soon to be visible)

Called when the object is about to become visible.

OnBecameInvisible (will not be visible)

Called when the object is about to become invisible.

OnPreRender (about to render)

This function is only used in scripts hosted by cameras. This message is fired when this camera starts rendering a scene.
Called before all rendering starts, this method is actually very elegant, I saw that most netizens have copied several usages of this method: adding scripts, setting titles, setting button client events, setting controls State, add script block.
Personally, I think there are more things that can be done before rendering. For example, can you consider doing some rendering optimization before rendering? Although there are already many plug-ins, if the program design is good, you can consider implementing a set of optimizations yourself. Fit your program.

OnRenderObject

This function is only used in scripts hosted by cameras. Triggered when the object created by Graphics.DrawMeshNow or other functions is drawn and rendered.

OnPostRender

This function is only used in scripts hosted by cameras. This message is fired when all renderings within this camera range are complete.

OnRenderImage

Triggered when all postprocessing effects of the image (only supported by the pro version) are rendered.

OnDrawGizmos (Gizmos rendering)

Gizmos are generally used by developers, referring to objects such as cameras and wireframes displayed in the scene editor during development. Therefore, the content in this method generally does not need to be released to the production environment.

GUI rendering

The work of user interface rendering will be performed in this step.

yield WaitForEndOfFrame (coroutine: end of frame)

This coroutine will be executed after the current frame is completely over. The coroutine runs as follows:

public class Test : MonoBehaviour
{
    
    
    void Awake()
    {
    
    
        Debug.Log("0");
        StartCoroutine(TestCoroutine());
        Debug.Log("2");
    }

    void Update()
    {
    
    
        Debug.Log("3 - Update");
    }

    void LateUpdate()
    {
    
    
        Debug.Log("4 - LateUpdate");
    }

    IEnumerator TestCoroutine()
    {
    
    
        Debug.Log("1");
        yield return new WaitForEndOfFrame();
        Debug.Log("5");                      // 当帧结束(触发WaitForEndOfFrame)后才会执行这条语句。 
    }
}

6. Pause phase

OnApplicationPause (application pause)

This method will be called when the application is suspended, and will be executed again from FixedUpdate after unpausing.

7. Exit phase

OnDestroy (Destroy)

Called when the object is destroyed, generally used to clean up memory.

OnApplicationQuit (application exits)

Called when the application exits, but sometimes it will fail. This method is unstable and can be used to save information before exiting under normal circumstances, but it is better to use a more secure method, because this method will not be called sometimes, such as Android environment.


For more information, please check the general catalog [Unity] Unity study notes catalog arrangement

Guess you like

Origin blog.csdn.net/xiaoyaoACi/article/details/119324146