{"id":960,"date":"2024-09-19T18:00:55","date_gmt":"2024-09-19T10:00:55","guid":{"rendered":"https:\/\/www.huangjiaqi-mise.site\/?p=960"},"modified":"2024-09-19T18:20:30","modified_gmt":"2024-09-19T10:20:30","slug":"building-a-simulation-system-with-unity-execution-order-of-event-functions","status":"publish","type":"post","link":"https:\/\/www.huangjiaqi-mise.site\/?p=960","title":{"rendered":"Building a Simulation System with Unity: Execution Order of Event Functions"},"content":{"rendered":"\t\t<div data-elementor-type=\"wp-post\" data-elementor-id=\"960\" class=\"elementor elementor-960\">\n\t\t\t\t\t\t<section class=\"elementor-section elementor-top-section elementor-element elementor-element-7d8609e elementor-section-boxed elementor-section-height-default elementor-section-height-default\" data-id=\"7d8609e\" data-element_type=\"section\">\n\t\t\t\t\t\t<div class=\"elementor-container elementor-column-gap-default\">\n\t\t\t\t\t<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-96b4286\" data-id=\"96b4286\" data-element_type=\"column\">\n\t\t\t<div class=\"elementor-widget-wrap elementor-element-populated\">\n\t\t\t\t\t\t<div class=\"elementor-element elementor-element-6dad7fb elementor-widget elementor-widget-text-editor\" data-id=\"6dad7fb\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t\t\t\t\t<h4>1. The Source of All Things \u2014 The MonoBehaviour Class<\/h4><p>MonoBehaviour is the base class for all scripts in Unity. It provides a range of functionalities for implementing behaviors in game objects. By inheriting from MonoBehaviour, users can create custom scripts to control the lifecycle of game objects, respond to events, and manage game logic. It has the following key features:<\/p><p><strong>Lifecycle Management<\/strong>: MonoBehaviour provides a series of event functions (such as `Awake()`, `Start()`, `Update()`, etc.) that help developers manage the lifecycle of objects.<\/p><p><strong>Component System<\/strong>: Unity uses a modular design, and MonoBehaviour allows you to modularize functionality, making it easier to reuse code across different game objects.<\/p><p><strong>Access to Unity API<\/strong>: Through MonoBehaviour, you can directly access many Unity features, such as the physics engine, rendering system, and input management.<\/p><p><strong>Coroutine Support<\/strong>: MonoBehaviour supports coroutines, allowing you to execute code over a period without blocking the main thread.<\/p><h4>2. What is the Script Lifecycle?<\/h4><p>The script lifecycle refers to the execution order and timing of MonoBehaviour scripts in Unity. Understanding the script lifecycle is essential for writing effective game logic. Below are the main lifecycle event functions of MonoBehaviour and their order. For specifics on other event functions, you can refer to the Unity documentation:<\/p><p>1. <strong>Awake()<\/strong><br \/>&#8211; **Timing**: Called when the script instance is loaded.<br \/>&#8211; **Purpose**: Used for variable or state initialization, typically executed before the game object is enabled.<\/p><p>2. <strong>OnEnable()<\/strong><br \/>&#8211; **Timing**: Called when the object is enabled.<br \/>&#8211; **Purpose**: Suitable for subscribing to events or performing initialization tasks.<\/p><p>3. <strong>Start()<\/strong><br \/>&#8211; **Timing**: Called before the first update.<br \/>&#8211; **Purpose**: Used for one-time initialization, ensuring all references are set.<\/p><p>4. <strong>Update()<\/strong><br \/>&#8211; **Timing**: Called once per frame.<br \/>&#8211; **Purpose**: Handles per-frame logic updates, such as input handling and object movement.<\/p><p>5. <strong>FixedUpdate()<\/strong><br \/>&#8211; **Timing**: Called at fixed time intervals.<br \/>&#8211; **Purpose**: Suitable for physics calculations (e.g., Rigidbody movement), as it executes at a fixed frequency.<\/p><p>6. <strong>LateUpdate()<\/strong><br \/>&#8211; **Timing**: Called after all Update calls.<br \/>&#8211; **Purpose**: Used for operations that need to execute after all other updates, such as camera follow.<\/p><p>7. <strong>OnDisable()<\/strong><br \/>&#8211; **Timing**: Called when the object is disabled.<br \/>&#8211; **Purpose**: Typically used to unsubscribe from events or clean up resources.<\/p><p>8. <strong>OnDestroy()<\/strong><br \/>&#8211; **Timing**: Called before the object is destroyed.<br \/>&#8211; **Purpose**: Used for resource release or cleanup tasks.<\/p><h4>3. What are Event Functions?<\/h4><p>Event functions are a set of special methods provided by the MonoBehaviour class in Unity to respond to specific events or conditions. These functions are automatically called in particular contexts, allowing developers to implement dynamic behaviors for game objects. Here are some common <span style=\"text-decoration: underline;\"><strong>event functions<\/strong><\/span> and their purposes:<\/p><p>&#8211; <strong>Awake()<\/strong>: Called when the script instance is loaded. Commonly used for variable initialization.<\/p><p>&#8211; <strong>OnEnable()<\/strong>: Called when the game object is enabled. Suitable for event subscription or initialization.<\/p><p>&#8211; <strong>Start()<\/strong>: Called before the first update. Used for one-time initialization.<\/p><p>&#8211; <strong>Update()<\/strong>: Called once per frame. Handles per-frame logic updates, such as input and movement.<\/p><p>&#8211; <strong>FixedUpdate()<\/strong>: Called at fixed time intervals. Suitable for physics calculations, like Rigidbody movement.<\/p><p>&#8211; <strong>LateUpdate()<\/strong>: Called after all Update calls. Used for operations that need to follow other updates, like camera follow.<\/p><p>&#8211; <strong>OnDisable()<\/strong>: Called when the object is disabled. Used for unsubscribing from events or cleaning up resources.<\/p><p>&#8211; <strong>OnDestroy()<\/strong>: Called before the object is destroyed. Used for releasing resources or performing cleanup tasks.<\/p><p><span style=\"text-decoration: underline;\"><strong>Physics and Collision Events:<\/strong><\/span><\/p><p>&#8211; <strong>OnCollisionEnter()<\/strong>: Called when a collision occurs.<br \/>&#8211; <strong>OnCollisionExit()<\/strong>: Called when a collision ends.<br \/>&#8211; <strong>OnTriggerEnter()<\/strong>: Called when an object enters a trigger.<br \/>&#8211; <strong>OnTriggerExit()<\/strong>: Called when an object exits a trigger.<\/p><p><span style=\"text-decoration: underline;\"><strong>User Input Events:<\/strong><\/span><\/p><p>&#8211; <strong>OnMouseDown()<\/strong>: Called when the mouse clicks on the game object.<br \/>&#8211; <strong>OnMouseUp()<\/strong>: Called when the mouse button is released.<\/p><h4>4. Code Example<\/h4><p>In the <a href=\"https:\/\/www.huangjiaqi-mise.site\/?p=893\">previous blog<\/a>, we introduced <strong>Coroutines<\/strong>. In this example, we will understand the execution flow of key event functions in Unity through code.<\/p>\t\t\t\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t<div class=\"elementor-element elementor-element-fa95e5a elementor-widget elementor-widget-html\" data-id=\"fa95e5a\" data-element_type=\"widget\" data-widget_type=\"html.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t<pre>\r\n<code>\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing UnityEngine;\r\n\r\npublic class ExecutionSequence : MonoBehaviour\r\n{\r\n\r\n    int counter;\/\/ start is called before the first frame updatevoid start()\r\n\r\n    \/\/ Start is called before the first frame update\r\n    void Start()\r\n    {\r\n        StartCoroutine(\"myCoroutine\"); \r\n        print(\"start ends.\");\r\n    }\r\n\r\n    \/\/ Update is called once per frame\r\n    void Update()\r\n    {\r\n        if (counter < 10) print(\"frame:\" + counter++);\r\n    }\r\n\r\n    IEnumerator myCoroutine() \r\n    {\r\n        print(\"step1\");\r\n        yield return null;\r\n        print(\"step2\"); \r\n        print(\"step3\");\r\n\r\n    }\r\n\r\n}\r\n<\/code>\r\n<\/pre>\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t<div class=\"elementor-element elementor-element-901aa7d elementor-widget elementor-widget-text-editor\" data-id=\"901aa7d\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t\t\t\t\t<h5>The execution order is as follows:<\/h5><p>1. First, the `Start` method is called, which starts the coroutine `myCoroutine`, and the console outputs <strong>&#8220;step1&#8221;<\/strong>.<br \/><br \/>2. The coroutine reaches `yield return null;`, effectively pausing execution until the next frame (after the next `Update` call). The console then outputs <strong>&#8220;start ends.&#8221;<\/strong>.<\/p><p>3. The `Update` method is called for the first time, and the `counter` starts counting from 0, outputting <strong>&#8220;frame: 0&#8221;<\/strong> to the console.<\/p><p>4. When the `Update` method runs in the next frame (second call), it outputs <strong>&#8220;frame: 1&#8221;<\/strong>.<\/p><p>5. The coroutine resumes execution, printing <strong>&#8220;step2&#8221; and &#8220;step3&#8221;<\/strong> to the console. At this point, all content of the coroutine has been executed.<\/p><p>6. The `Update` method continues to be called <strong>until the `counter` reaches 9<\/strong>.<\/p>\t\t\t\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t<div class=\"elementor-element elementor-element-de94017 elementor-widget elementor-widget-image\" data-id=\"de94017\" data-element_type=\"widget\" data-widget_type=\"image.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<img fetchpriority=\"high\" decoding=\"async\" width=\"380\" height=\"595\" src=\"https:\/\/www.huangjiaqi-mise.site\/wp-content\/uploads\/2024\/09\/execution-sequence.png\" class=\"attachment-large size-large wp-image-954\" alt=\"\" srcset=\"https:\/\/www.huangjiaqi-mise.site\/wp-content\/uploads\/2024\/09\/execution-sequence.png 380w, https:\/\/www.huangjiaqi-mise.site\/wp-content\/uploads\/2024\/09\/execution-sequence-192x300.png 192w\" sizes=\"(max-width: 380px) 100vw, 380px\" \/>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t<div class=\"elementor-element elementor-element-990dd8c elementor-widget elementor-widget-text-editor\" data-id=\"990dd8c\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t\t\t\t\t<p><a href=\"https:\/\/www.huangjiaqi-mise.site\/?p=946\" target=\"_blank\" rel=\"noopener\">\u3010\u4e2d\u6587\u7248\u8bf7\u70b9\u51fb\u8fd9\u91cc\u3011<\/a><\/p>\t\t\t\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/section>\n\t\t\t\t<section class=\"elementor-section elementor-top-section elementor-element elementor-element-1276e4b elementor-section-boxed elementor-section-height-default elementor-section-height-default\" data-id=\"1276e4b\" data-element_type=\"section\">\n\t\t\t\t\t\t<div class=\"elementor-container elementor-column-gap-default\">\n\t\t\t\t\t<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-8dcb03e\" data-id=\"8dcb03e\" data-element_type=\"column\">\n\t\t\t<div class=\"elementor-widget-wrap elementor-element-populated\">\n\t\t\t\t\t\t<div class=\"elementor-element elementor-element-a975531 elementor-widget-divider--separator-type-pattern elementor-widget-divider--view-line elementor-widget elementor-widget-divider\" data-id=\"a975531\" data-element_type=\"widget\" data-widget_type=\"divider.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t\t\t<div class=\"elementor-divider\" style=\"--divider-pattern-url: url(&quot;data:image\/svg+xml,%3Csvg xmlns=&#039;http:\/\/www.w3.org\/2000\/svg&#039; preserveAspectRatio=&#039;none&#039; overflow=&#039;visible&#039; height=&#039;100%&#039; viewBox=&#039;0 0 20 16&#039; fill=&#039;none&#039; stroke=&#039;black&#039; stroke-width=&#039;1&#039; stroke-linecap=&#039;square&#039; stroke-miterlimit=&#039;10&#039;%3E%3Cg transform=&#039;translate(-12.000000, 0)&#039;%3E%3Cpath d=&#039;M28,0L10,18&#039;\/%3E%3Cpath d=&#039;M18,0L0,18&#039;\/%3E%3Cpath d=&#039;M48,0L30,18&#039;\/%3E%3Cpath d=&#039;M38,0L20,18&#039;\/%3E%3C\/g%3E%3C\/svg%3E&quot;);\">\n\t\t\t<span class=\"elementor-divider-separator\">\n\t\t\t\t\t\t<\/span>\n\t\t<\/div>\n\t\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/section>\n\t\t\t\t<\/div>\n\t\t","protected":false},"excerpt":{"rendered":"<p>1. The Source of All Things \u2014 The MonoBehaviour Class M [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"default","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[18],"tags":[],"class_list":["post-960","post","type-post","status-publish","format-standard","hentry","category-unity"],"_links":{"self":[{"href":"https:\/\/www.huangjiaqi-mise.site\/index.php?rest_route=\/wp\/v2\/posts\/960","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.huangjiaqi-mise.site\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.huangjiaqi-mise.site\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.huangjiaqi-mise.site\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.huangjiaqi-mise.site\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=960"}],"version-history":[{"count":16,"href":"https:\/\/www.huangjiaqi-mise.site\/index.php?rest_route=\/wp\/v2\/posts\/960\/revisions"}],"predecessor-version":[{"id":998,"href":"https:\/\/www.huangjiaqi-mise.site\/index.php?rest_route=\/wp\/v2\/posts\/960\/revisions\/998"}],"wp:attachment":[{"href":"https:\/\/www.huangjiaqi-mise.site\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=960"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.huangjiaqi-mise.site\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=960"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.huangjiaqi-mise.site\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=960"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}