Unity's Life cycle

Life cycle

This page is an effort to thoroughly document the different life cycles in Unity... contribution needed!

I'm using it for myself right now because I keep making the same tests to figure out the exact life-cycles, and figured this would be a good place to finally centralize the info.


Contents

 [hide] 
  • 1 Behaviour events
    • 1.1 Notes
    • 1.2 Static Constructor
    • 1.3 Constructor
    • 1.4 0 : Awake
    • 1.5 0 : OnEnable
    • 1.6 [0 : OnLevelWasLoaded]
    • 1.7 0 : Main
    • 1.8 0 : Start
    • 1.9 0 : Update (first call)
    • 1.10 0 : LateUpdate (first call)
    • 1.11 0 : OnDrawGizmos (first call)
    • 1.12 0 : OnDrawGizmosSelected (first call)
    • 1.13 [+1 : OnNetworkLoadedLevel]
    • 1.14 +x : OnApplicationQuit
    • 1.15 +x : OnDisable
    • 1.16 Example
  • 2 Collisions / Physics
  • 3 GUI
  • 4 Network life cycle
    • 4.1 OnDisconnectedFromServer

Behaviour events

Notes

  • Supposing your scene starts at frame 0 (or an object gets activated, or a component gets added, or an object gets created)...
  • Inactive objects "don't count", think of them as basically not being on the scene at all.
  • Lots more to cover...

Static Constructor

This is called by .net as your assemblies are being loaded. The C# Reference makes very few guarantees about exactly when it will be called, but it does state that before any part of a class can be referenced its static constructor will be called.

If working from the editor, when you save a script (and thus force a recompilation), your static constructor is likely to be called immediately as Unity loads the built DLL. It will not likely be run again.

On a deployed game, this constructor will be called early in Unity's loading process.

Constructor

Unity will call the default constructor of any object but at seemingly random times. While editing a game, the constructor is likely to be called immediately after saving a script (forcing a recompilation).

Do not use a constructor to assign values to fields. Unity's Awake() is designed specifically for that purpose.

0 : Awake

This is the one and only event that will ALWAYS fire (unless the object is inactive, see above). It will still fire if the object is active but the script is disabled.

0 : OnEnable

Not called if the behaviour is disabled.

[0 : OnLevelWasLoaded]

Not called on the first level.

Not called if the object is created once the level is loaded.

0 : Main

Not called if the behaviour is disabled.

Undocumented. 
In a Javascript behaviour, this is where your inline instructions go after compilation, but it's actually usable in C# as well.

Only think of it as a pre-Start, not another round of events. 
All Awakes are called, then all Main & Start are called, NOT all Awake, all Main, then all Start. 
Consider components Script1 & Script2, Script1 being first in the component list, the call order will be:

  • Awake Script1
  • Awake Script2
  • Main Script1
  • Start Script1
  • Main Script2
  • Start Script2

0 : Start

Not called if the behaviour is disabled.

0 : Update (first call)

Not called if the behaviour is disabled.

0 : LateUpdate (first call)

Not called if the behaviour is disabled.

0 : OnDrawGizmos (first call)

Editor-only. Called even if the behaviour is disabled.

0 : OnDrawGizmosSelected (first call)

Editor-only, called only if the object is selected in the hierarchy view. Called even if the behaviour is disabled.

[+1 : OnNetworkLoadedLevel]

Only called if the level was network-loaded.

This event isn't actually built-in, but fired by the NetworkLevelLoad script that lots of people are using. 
The +1 delay is also introduced by this script, but I'm not sure it would be wise to try and remove it.

+x : OnApplicationQuit

+x : OnDisable

Example

Don't take my word for it, try it for yourself!

  • You'll notice that if you just drop this script wherever and press play, everything starts at frame 1.
    I don't know if frame 0 even exists (it's called frameCount after all), or if it's used for internal initialization...
  • If you load a scene from another one, you'll notice there is a one-frame delay (eg if this script is in a scene that was loaded as soon as the game starts, everything starts at frame 2).
using UnityEngine;
using System.Collections;
 
public class TestLifeCycle : MonoBehaviour
{
	void Awake()
	{
		logFrame("Awake");
	}
	void Main()
	{
		logFrame("Main");
	}
	void Start()
	{
		logFrame("Start");
	}
 
	void OnLevelWasLoaded()
	{
		logFrame("OnLevelWasLoaded");
	}
	void OnNetworkLoadedLevel()
	{
		logFrame("OnNetworkLoadedLevel");
	}
 
	void OnEnable()
	{
		logFrame("OnEnable");
	}
	void OnDisable()
	{
		logFrame("OnDisable");
	}
	void OnApplicationQuit()
	{
		logFrame("OnApplicationQuit");
	}
 
 
	void Update()
	{
		logFrame("Update");
	}
	void LateUpdate()
	{
		logFrame("LateUpdate");
	}
	void FixedUpdate()
	{
		logFrame("FixedUpdate");
	}
	void LateFixedUpdate()
	{
		logFrame("LateFixedUpdate");
	}
 
	void OnDrawGizmos()
	{
		logFrame("OnDrawGizmos");
	}
	void OnDrawGizmosSelected()
	{
		logFrame("OnDrawGizmosSelected");
	}
 
 
	static void logFrame(string message)
	{
		Debug.Log(Time.frameCount + " - " + message);
	}
}

Collisions / Physics

TODO... 
explain FixedUpdate here, relation with OnCollisionXXX

GUI

TODO... 
explain EventType

Network life cycle

TODO... 
explain MasterServer connection, peer connection / disconnection, etc...

OnDisconnectedFromServer

If a method call Network.Disconnect(), OnDisconnectedFromServer will be called instantly (whether in the same script or any other script that subscribes to this callback).

Example:

	void Disconnect()
	{
		logFrame("before Disconnect");
		Network.Disconnect();
		logFrame("after Disconnect");
	}
	void OnDisconnectedFromServer()
	{
		logFrame("OnDisconnectedFromServer");
	}

will lead to the following output:

before Disconnect
OnDisconnectedFromServer
after Disconnect

This behaviour is opposed to delayed callbacks, that occur one frame later than the event that triggered them (for example OnTriggerEnter is called the frame after the collision visually occurs). Also note that Debug.Break() will not interrupt the current call stack, merely pause the editor at the end of the current frame. TODO: reference instant/delayed callbacks.

原文:http://wiki.unity3d.com/index.php?title=Life_cycle


在unity4中如下图






在unity5中

Execution Order of Event Functions

In Unity scripting, there are a number of event functions that get executed in a predetermined order as a script executes. This execution order is described below:

Editor

  • Reset: Reset is called to initialize the script’s properties when it is first attached to the object and also when the Reset command is used.

First Scene Load

These functions get called when a scene starts (once for each object in the scene).

  • Awake: This function is always called before any Start functions and also just after a prefab is instantiated. (If a GameObject is inactive during start up Awake is not called until it is made active, or a function in any script attached to it is called.)
  • OnEnable: (only called if the Object is active): This function is called just after the object is enabled. This happens when a MonoBehaviour instance is created, such as when a level is loaded or a GameObject with the script component is instantiated.

Note that for objects added to the scene, the Awake and OnEnable functions for all scripts will be called before Start, Update, etc are called for any of them. Naturally, this cannot be enforced when an object is instantiated during gameplay.

Before the first frame update

  • Start: Start is called before the first frame update only if the script instance is enabled.

For objects added to the scene, the Start function will be called on all scripts before Update, etc are called for any of them. Naturally, this cannot be enforced when an object is instantiated during gameplay.

In between frames

  • OnApplicationPause: This is called at the end of the frame where the pause is detected, effectively between the normal frame updates. One extra frame will be issued after OnApplicationPause is called to allow the game to show graphics that indicate the paused state.

Update Order

When you’re keeping track of game logic and interactions, animations, camera positions, etc., there are a few different events you can use. The common pattern is to perform most tasks inside the Update function, but there are also other functions you can use.

  • FixedUpdate: FixedUpdate is often called more frequently than Update. It can be called multiple times per frame, if the frame rate is low and it may not be called between frames at all if the frame rate is high. All physics calculations and updates occur immediately after FixedUpdate. When applying movement calculations inside FixedUpdate, you do not need to multiply your values by Time.deltaTime. This is because FixedUpdate is called on a reliable timer, independent of the frame rate.

  • Update: Update is called once per frame. It is the main workhorse function for frame updates.

  • LateUpdate: LateUpdate is called once per frame, after Update has finished. Any calculations that are performed in Update will have completed when LateUpdate begins. A common use for LateUpdate would be a following third-person camera. If you make your character move and turn inside Update, you can perform all camera movement and rotation calculations in LateUpdate. This will ensure that the character has moved completely before the camera tracks its position.

Rendering

  • OnPreCull: Called before the camera culls the scene. Culling determines which objects are visible to the camera. OnPreCull is called just before culling takes place.
  • OnBecameVisible/OnBecameInvisible: Called when an object becomes visible/invisible to any camera.
  • OnWillRenderObject: Called once for each camera if the object is visible.
  • OnPreRender: Called before the camera starts rendering the scene.
  • OnRenderObject: Called after all regular scene rendering is done. You can use GL class or Graphics.DrawMeshNow to draw custom geometry at this point.
  • OnPostRender: Called after a camera finishes rendering the scene.
  • OnRenderImage: Called after scene rendering is complete to allow postprocessing of the screen image.
  • OnGUI: Called multiple times per frame in response to GUI events. The Layout and Repaint events are processed first, followed by a Layout and keyboard/mouse event for each input event.
  • OnDrawGizmos Used for drawing Gizmos in the scene view for visualisation purposes.

Coroutines

Normal coroutine updates are run after the Update function returns. A coroutine is a function that can suspend its execution (yield) until the given YieldInstruction finishes. Different uses of Coroutines:

  • yield The coroutine will continue after all Update functions have been called on the next frame.
  • yield WaitForSeconds Continue after a specified time delay, after all Update functions have been called for the frame
  • yield WaitForFixedUpdate Continue after all FixedUpdate has been called on all scripts
  • yield WWW Continue after a WWW download has completed.
  • yield StartCoroutine Chains the coroutine, and will wait for the MyFunc coroutine to complete first.

When the Object is Destroyed

  • OnDestroy: This function is called after all frame updates for the last frame of the object’s existence (the object might be destroyed in response to Object.Destroy or at the closure of a scene).

When Quitting

These functions get called on all the active objects in your scene:

  • OnApplicationQuit: This function is called on all game objects before the application is quit. In the editor it is called when the user stops playmode. In the web player it is called when the web view is closed.
  • OnDisable: This function is called when the behaviour becomes disabled or inactive.

Script Lifecycle Flowchart

The following diagram summarises the ordering and repetition of event functions during a script’s lifetime.














你可能感兴趣的:(Unity's Life cycle)