I thought this was trivial at start, but after looking and searching, I haven’t found a solution.
How can you retrieve the name of the animation currently playing on a gameobject?
I certainly know of isplaying(), but there’s no overload for it, and it only returns a boolean.
I think it’s unnecessarily expensive to cycle through the animation list to find which one is playing.
So basically i need to get the name of the animation currently playing. Any way to do that?
You can’t, because multiple clips can be playing simultaneously - i.e. there is no current. You can iterate through the animation states, look at the clips and weights, as you’re mentioning:
var bestWeight = -1.0;
var playing : String;
for (s : AnimationState in animation) {
if (s.enabled && s.weight > bestWeight) {
playing = s.name;
bestWeight = s.weight;
}
}
Alternatively, record the animation you last played when you start/play/queue it.
If you say what you’re ultimately trying to achieve by knowing “what is playing” (i.e. what that might mean in your game), there may be other possibilities.
I know that this post is relatively old now… For anyone else looking over this:
What you should do is assign an integer value parameter to track the current state. Then you can check against the variable to determine which state it is in.
AnimationState = 0 (Idle)
AnimationState = 1 (Walking) etc…
animator = GetComponent(Animator);
int isPlayingWalking = animator.GetInteger(“AnimationState”);
So if your animation is within a certain state, whether there are multiple animations or not, you can determine whether it is playing by your parameter.
For the beginners ,debuggers that looking for other ways and for the other rare occasions, here is semi-manual way to do that:
Let the current animation find you, Unity Docs - Animation Events. Add an event to the animation you are looking for. This event should call a method in your script of gameobject. Let’s call that method as printAnimationEvent with String parameter. Within that method you can print the name of the animation.
public void printAnimationName(string name) {
print(name);
}