- Home /
Clarification on updates, physics events order and frequency?
Is there a summary clarifying when, how often, and in what order all the following MonoBehaviour messages are triggered: Update, FixedUpdate, OnCollisionEnter (and all other col/trigger events)? I could probably figure it out by trial and error, but could someone point me to a doc that clarifies all this stuff? Cheers.
Answer by aldonaletto · Dec 22, 2011 at 08:27 AM
Unity has two main "cycles" running independently: the update cycle and the physics cycle (see Scripting Overview). The update cycle is synced to the frame rate: before rendering each frame, Unity first calls all Update functions in all scripts, then calls all LateUpdate functions. Other functions that are called in the update cycle are the camera events (OnPreCull, OnPreRender etc.). Coroutines are also tied to the update cycle: when an yield is executed, the coroutine is suspended, and will resume in the next update cycle (not sure if before or after Update).
The physics cycle is where all physics related stuff happens (physics calculation and collision detection); it has a "fixed" rate set in the Time Manager - 50 times per second by default (20mS). Unity tries to keep this rate, but some extremely long Update may disturb this. The function FixedUpdate is called in all scripts during the physics cycle, as well as all the collision/trigger events. From my experience, collision/trigger events seem to be called after the FixedUpdates, but I have not extensively tested this.
Besides these two main cycles, Unity has also the "GUI cycle": the function OnGUI is called before rendering the GUI elements and every time a system input event (key, button, mouse) is reported. The GUI cycle may thus happen multiple times during one single update cycle.
As a rule of thumb, all Input.WhateverDown/Up functions (GetKeyDown, GetButtonUp etc.) must be called only in the update cycle (Update, LateUpdate). When a key is pressed, for instance, GetKeyDown returns true for the whole update cycle; if called inside OnGUI (a common error) it may return true several times.