Script life cycle in Unity3d (Monobehaviour lifecycle)

Source: Internet
Author: User

From: http://blog.csdn.net/qitian67/article/details/18516503

Recently in a small example, found that the class inherits from the class of monobehaviour, there are many methods, so it is necessary to ask a question: So many methods, the implementation of the order is how it. How is the internal management? So on the internet to find a lot of information, found that Richard Fine in 2012 has published an article, and is quite deep, and very reasonable, here with some of my attempts and thinking, to share with you.

First put on the picture, we have an intuitive understanding:

Next, to explain: the first way to do this is awake, which is the beginning of the life cycle, the initialization code for activation, you can generally disable the current script in this place: This.enable=false, if you do, Will jump directly to the Ondisable method once, and any other methods will no longer be executed.

If the current script is in a usable state, the normal execution order is to continue to execute onenable down, and of course we can implement this script component's startup in another script: this.enab=true;

If the Start method is not executed, it will be executed once and if it has been executed, it will not be executed again. What's the meaning of this? We can disable This.enable=false in a script, and then turn it on to onenable, then proceed down to find that start has been executed and will no longer be executed. For example: When first enabled, the initial position of the monster is set at the (0,0,0) point, then the monster may have a position change, and then disabled, again enabled, will not let the monster back to the original (0,0,0) position.

Continue backwards, that is, update, then fixupdate, then lateupdate, if Reset is written back, it will go back to update, the 4 events can be circulated.

And then go back to the Render module (Rendering), and one of the most important ways is Ongui, which is used to draw the graphical interface. Of course, if you use Ngui, you don't have to think about this life cycle.

Then backwards, is the unloading module (TearDown), here there are two methods ondisable and OnDestroy. When disabled (Enable=false), the Ondisable method is executed, but at this time the script is not destroyed, and in this state it can be returned to the Onenable State (enable=true). When manually destroyed or the attached game object is destroyed, OnDestroy is executed and the current script's life cycle ends.

It is particularly emphasized that although C # can be used to write code here, the life cycle of this class constructed object is completely different from the life cycle of the monobehaviour.

You can use the following example: to validate a script (two scripts are added to the same game object):

Script 1monster1:

void Onbecameinvisible ()
{
Debug.Log ("invisible");
Monstercontroller MC1 = this.gameobject.getcomponent<monstercontroller> ();
mc1.enabled = false;
}


void Onbecamevisible ()
{
Debug.Log ("visible");
Monstercontroller MC1 = this.gameobject.getcomponent<monstercontroller> ();
Mc1.enabled = true;
}

Script 2MonsterController:

void Awake ()
{
Debug.Log ("Awake");
this.enabled = false;
}


void Onenable ()
{
Debug.Log ("Enable");
This.enabled = true;
}


void Start ()
{
Debug.Log ("Start");
This.gameObject.SetActive (FALSE);
}


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


void Ongui ()
{
Debug.Log ("GUI");
}
void Ondisable ()
{
Debug.Log ("Disable");
}


void OnDestroy ()
{
Debug.Log ("destroy");
}

If you feel that there is something wrong, please correct me, for technical progress, we work together.

Richard Fine's article address: click to read

Supplemental website Information: Order of execution of event functions

There are many event functions in the Unity script that run as scripts in the preset order. The order of execution is as follows: loading the first scene

These functions are called when the scene is started (once for each object in the scene). Awake: This function is always called before any Start function is called and after the preset is instantiated. (If the Game object (Gameobject) is inactive during startup, the Awake function is called until it is active or when it calls a function in any script that is added to itself.) The Scarlet Letter part is not mentioned in the figure, especially need to pay attention to ... The green part clearance test is incorrect onenable: (This function is called only when the object is active): The program calls this function immediately after the object is enabled.   This behavior occurs after an instantiated monobehaviour is created, such as when a level is loaded or when a game object (Gameobject) with a script component is instantiated. before the first frame update   Start: Whenever you enable a script instance, you can call the start function before you update the first frame. interpolated Frames Onapplicationpause: When a program detects a pause, this function is called at the end of the frame, which is effective during regular frame updates.   When Onapplicationpause is called, the program runs another frame to display a graph that prompts for a paused state. Update Order

There are several different events that can help you track game logic and interactions, animations, camera locations, and more.   The common approach is to run most of the tasks in the update () function, but you can also use other functions: Fixedupdate: Typically, fixedupdate () is called more frequently than Update (). If the frame rate is low, you can call this function multiple times in a frame, and if the frame rate is high, you may not be able to call this function between frames at all. All physical calculations and updates are performed immediately after the program calls Fixedupdate (). When you apply a mobile calculation in fixedupdate (), you do not need to multiply your values with time.deltatime.   This is because the program calls Fixedupdate () on a reliable timer, regardless of the frame rate. Update: the update () function is called once per frame.   It is the primary workhorse function for frame updates. Lateupdate: After the Update () call is completed, Lateupdate () is called on each frame. All calculations performed in Update () will end before the start of Lateupdate (). The general usage record of lateupdate () is tracked by a third person camera. If you move and rotate roles in Update (), you can calculate all camera moves and rotations in lateupdate (). This ensures that the role is fully moved before the camera tracks its position.RenderingOnprecull: Call this function before the camera rejects the scene. The objects visible to the camera depend on culling. The Onprecull function call occurs before culling. Onbecamevisible/onbecameinvisible: This function is called when the object is visible/invisible to the camera. Onwillrenderobject: This function is called once for each camera if the object is visible. OnPreRender: Call this function before the camera starts rendering the scene. Onrenderobject: This function is called after all normal scene rendering has been completed. At this point, you can use the GL class or Graphics.drawmeshnow to draw the custom geometry. Onpostrender: This function is called after the camera has finished rendering the scene. Onrenderimage (Professional Edition only): This function is called after the scene rendering is complete to post-process the screen image. Ongui: This function is called multiple times on each frame in response to GUI events. The program first processes the layout and Repaint events, and then processes the layout and keyboard/mouse events for each input event. Ondrawgizmos is used to draw small icons (gizmos) in the scene view for visualization purposes.Collaborative Programs

The

Normal co-program update runs after the update function is returned. A synergistic program is a function that can stop running (yield) itself until a given yieldinstruction ends and then continues to run. Different uses of the synergistic Program (coroutines): After yield;  all the Update functions on the next frame, the co-program will continue to run. Yield Waitforseconds (2);  after the specified time delay, after calling all the Update functions for this frame, continue to run yield waitforfixedupdate ();  call all on all scripts After Fixedupdate continues to run yield www  complete WWW download to continue running. Yield Startcoroutine (MyFunc);  connect the collaboration program and wait for MyFunc coroutine to end first.   object is destroyed ondestroy:  this function on the last frame of the current object after all frame updates have been completed (possibly in response Object.destroy or destroy the object when the scene is closed).   when exiting

The

program calls these functions on all the active objects of the scene: onapplicationquit:  The program calls this function on all game objects before exiting the application. In the editor, the program calls this function when the user stops the playback mode. In a Web page player, this function is called when the Page view is closed. ondisable:  This function is called when the behavior is disabled or inactive.   in summary, the order of execution for any given script is: call all awake calls all Start simultaneously (toward variable delta time) all Fixedupdate functions physical simulations Onenter/exit/stay Trigger function Onenter/exit/stay Collision function   Rigid body interpolation apply events such as transform.position and rotate onmousedown/onmouseup all Update functions optimize animations to advanced, blend, and apply animations to To transform all lateupdate function rendering   hints The co-program runs after all the Update functions have ended.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.