Event functions are a set of predefined callbacks that all MonoBehaviour script components can potentially receive. The callbacks are triggered by various Unity Editor and Engine events, including:
Implement the appropriate method signature in your MonoBehaviour
-derived class to allow your game objects to react to the source events.
Refer to the MonoBehaviour Scripting API reference page for a full list of the available callbacks, where they are listed under Messages. The rest of this section gives an overview of some of the key groups of event functions.
A game is like an animation where the animation frames are generated on the fly. A key concept in games programming is making changes to position, state, and behavior of objects just before each frame is rendered. The Update
function is the main place for this kind of code in Unity. Update
is called before the frame is rendered and also before animations are calculated.
void Update() {
float distance = speed * Time.deltaTime * Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * distance);
}
The physics system also updates in discrete time steps in a similar way to the frame rendering. A separate event function called FixedUpdate
is called just before each physics update. Since the physics updates and frame updates don’t occur with the same frequency, you can get more accurate results from physics code if you place it in the FixedUpdate
function rather than Update
.
void FixedUpdate() {
Vector3 force = transform.forward * driveForce * Input.GetAxis("Vertical");
rigidbody.AddForce(force);
}
It’s also sometimes useful to make additional changes at a point after the Update
and FixedUpdate
functions have been called for all objects in the sceneA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary, and after all animations have been calculated. Some examples of this scenario are:
The LateUpdate
function can be used for these kinds of situations.
void LateUpdate() {
Camera.main.transform.LookAt(target.transform);
}
It’s often useful to be able to call initialization code in advance of any updates that occur during gameplay. The Start function is called before the first frame or physics update on an object. The Awake function is called for each object in the scene at the time when the scene loads. Note that although the various objects’ Start
and Awake
functions are called in arbitrary order, all instances of Awake
will have finished before the first Start
is called. This means that code in a Start
function can make use of other initializations previously carried out in the Awake
phase.