Working with Animation Events in Unity
At first glance, when a programmer sees the word event, he can imagine a code like this…
Well, today it’s not about that type of events.
In this blog we are going to learn about a new type of events in Unity: Animation events
About this, Mohamed Hijazi says: Animation events basically allow you to call a function or method directly from the animation clip at a specific frame/time that you specify
Also, its implementation is very different from the usual way.
Creating an Animation event
First at all, usually you can create a script, for instance, from the project window, and it inherits from MonoBehavior
. An animation event can be created only in the inspector while selecting the animation, and the code that appears is very different, and inherits from StateMachineBehavior
For our project, we need to set up some stuff
- In
Player.cs
, create a reference forLedgeChecker
calledactiveLedge
- In LedgeChecker.cs, create a Vector3 reference for the
standPos
inLedgeChecker.cs
- In OnTriggerEnter, add a parameter
this
when callingGrabLedge()
- Create a method of type
Vector3 GetStandPos()
to return standPos - Set the Player’s position to
GetStandPos()
- Place the player in the exact place where the climbUp animation finishes to get the
standupPos
value - As it will be a modular script, we need to set that value automatically. For this, you can create a reference for
standPos
inPlayer.cs
and modify it in the inspector when you have found the correct position
Animation events
Now, in the climbUpBehavior.cs
script, we have the method public override void OnStateExit()
that will be executed after finishing the animation and contains the parameter Animator animator
.
With this parameter we can access the Player gameobject to set its new position with ClimbUpComplete()