1.2 Getting Started: Animation Events
In this section, you'll learn how to add events to AnimationClipAssets
and react to these events in code.
Open the scene at All Samples/1 - Basics/2 - Animation Events/DMotion - Basic - AnimationEvents.unity
and hit play. Make sure you have the console open. You'll see the same animation from the previous example, but now it logs "Footstep raised!" every time the robot foot hits the ground.
If you check out the clip at All Samples/1 - Basics/2 - Animation Events/1.2_AnimationEvents_Walk.asset
you'll see it has 2 events (white marker) in it's event timeline.
Note: The Preview Object
should have been automatically selected. But if you don't see any preview, just select the LowPolyRobot
fbx in the Preview Object
field
Here's the timeline controls:
Control | Action |
---|---|
Red control | Drag to scrub the animation preview |
Event Marker | Drag to set the animation time in which the event should be triggered |
Add Event | Double click the empty space in the timeline, or click the + icon at the right |
Remove Event | Select the event marker and click the X button at the right |
As mentioned above, you can create a new event by double clicking empty space in the timeline, and adjust it's position. The second thing that an animation event needs is a AnimationEventName
, which is used to identify the event in code.
In DMotion, AnimationEventName
are empty scriptable objects that you can create via Create -> DMotion -> Event Name
. This makes it easier and less error prone to re-use event names across the project. After creating a new event name, you can assign it to your Animation Event in the clips editor.
Handling animation events in code is super simple, the code below (see AnimationEventsSampleSystem
) achieves it:
[BurstCompile]
[RequireMatchingQueriesForUpdate]
public partial struct AnimationEventsSampleSystem : ISystem
{
private static readonly int FootstepEventHash = StateMachineParameterUtils.GetHashCode("EV_Footstep");
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<AnimationEventsSample>();
}
public void OnDestroy(ref SystemState state)
{
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
foreach (var raisedEvents in SystemAPI.Query<DynamicBuffer<RaisedAnimationEvent>>())
{
if (raisedEvents.WasEventRaised(FootstepEventHash, out var index))
{
var e = raisedEvents[index];
Debug.Log(FixedString.Format("Footstep event raised by entity: {0}", e.Entity.Index));
}
}
}
}
DMotion handles with raising events at the appropriate time, and cleaning up the RaisedAnimationEvent
buffer every frame, so you only need to react to the event.
This section showed you how to create and handle animation events in DMotion. In the next section we'll explore how to play clips through code.