askvity

How do you add events to animation clips in Unity?

Published in Unity Animation 2 mins read

To add events to animation clips in Unity, you select the animation clip in the Animation window and then use the events track to insert event markers at specific frames. These markers trigger functions in your scripts when the animation playback reaches them.

Here's a breakdown of the process:

  1. Open the Animation Window: Go to Window > Animation > Animation to open the Animation window.
  2. Select the GameObject: Select the GameObject in your scene that has the Animator component and the animation you want to modify.
  3. Select the Animation Clip: In the Animation window, choose the specific animation clip from the dropdown menu.
  4. Navigate to the desired frame: Move the timeline cursor to the frame where you want to add an event. You can drag the cursor or use the frame number input.
  5. Add an Animation Event: Click the "Add Event" button (it usually looks like a small marker or a plus icon located above the timeline in the animation window). This will create an event marker at the current frame.
  6. Define the Event:
    • In the Inspector window (with the event marker selected), specify the function name you want to call on the associated script.
    • Choose the script where the target function resides; that script must be attached to the same GameObject (or a child) the animator is on.
    • Optionally, you can pass parameters to the function, such as integers, floats, strings, objects, or animation clip events.

Example:

Let's say you have an animation clip called "Attack" and you want to trigger a function called DealDamage when the character swings their sword.

  1. Select your character GameObject.
  2. Open the Animation window and select the "Attack" animation clip.
  3. Move the timeline to the point where the sword should hit the enemy.
  4. Click the "Add Event" button.
  5. In the Inspector, enter DealDamage as the Function name.
  6. Ensure you have a script attached to your character that contains a DealDamage function (e.g., public void DealDamage() { ... }).

Now, when the animation plays and reaches that frame, the DealDamage function will be called.

Related Articles