Animation events let you run code at specific times during an animation. This helps your game react exactly when something happens in the animation.
0
0
Animation events in Unity
Introduction
You want to play a sound exactly when a character's foot hits the ground.
You want to trigger a particle effect when a sword swing hits an enemy.
You want to change a game state right when an animation finishes.
You want to call a function to spawn an object during an animation.
You want to sync gameplay actions with animation frames.
Syntax
Unity
void FunctionName() {
// Your code here
}
// In Unity Editor, add an Animation Event to call FunctionName at a specific frameAnimation events call functions in the script attached to the animated GameObject.
The function must be public or private and have zero or one parameter (float, int, string, or AnimationEvent).
Examples
This function can be called by an animation event to play a footstep sound.
Unity
public void PlayFootstepSound() {
Debug.Log("Footstep sound played");
}This function takes a string parameter from the animation event to spawn a named effect.
Unity
public void SpawnEffect(string effectName) {
Debug.Log($"Spawn effect: {effectName}");
}Sample Program
This script has a function that can be called by an animation event. When the animation reaches the event frame, it prints a message to the console.
Unity
using UnityEngine; public class AnimationEventExample : MonoBehaviour { public void OnAnimationHit() { Debug.Log("Animation hit event triggered!"); } }
OutputSuccess
Important Notes
You add animation events inside the Animation window in Unity by selecting a frame and clicking the Add Event button.
Make sure the function name in the event matches exactly the function in your script.
Animation events only work on animations controlled by the Animator component.
Summary
Animation events let you run code at exact moments during animations.
Functions called by animation events can have zero or one parameter.
Add animation events in the Unity Animation window on specific frames.