Daniel Lip
Daniel Lip

Reputation: 11319

How can I check if Animator ended playing specific State animation?

This way it's getting inside all the time while the animation state is playing :

void Update()
    {
        if (this.animator.GetCurrentAnimatorStateInfo(0).IsName("Stand Up"))
        {
            string tt = "";
        }
    }

So I tried to add ! to check if it false :

void Update()
    {
        if (!this.animator.GetCurrentAnimatorStateInfo(0).IsName("Stand Up"))
        {
            string tt = "";
        }
    }

but this way it's never getting inside even if the state animation finished playing.

I have one Base Layer in the animator controller.

Upvotes: 1

Views: 311

Answers (1)

HumanWrites
HumanWrites

Reputation: 945

NOTE: The solution below is only really relevant if your animation isn't looping and I assume "StandUp" is non-looping. Otherwise, the event will be raised every time the animation loops.

In my opinion, you'd be better off raising an animation event.

You can raise an event from the specific animation in question by adding an event marker to the animation timeline.

Creating an animation event

Then when you click on the event marker at the top of the timeline, you will see some options in the inspector.

Register event handler

Then, you will need to supply a name for the event handler that you want to handle this event e.g MyEventRaised and attach a script to the object that has you animator component.

Add animation event handler script

Inside that script you can add the handler that you want for the event.

using System;

public class MySpriteEventHandlerScript:MonoBehaviour 
{
    public EventHandler MyEventHandler;

    public void MyEventRaised()
    {
        MyEventHandler?.Invoke(this, EventArgs.Empty);
    }
}

Then, in the any script that you want to respond to the event that you've created, you can just get a reference to the event handler script attached to your animated object and register some code with the MyEventHandler event handler.

private MySpriteEventHandlerScript _MyEventHandlerScript;

void Start() 
{
    _MyEventHandlerScript = GameObject.FindGameObjectWithTag("MySprite").GetComponent<MySpriteEventHandlerScript>();
    // Register some code to do something when the handler is invoked
    _MyEventHandlerScript.MyEventHandler += TheCodeToRun;
}

// Create the necessary method in your class
private void TheCodeToRun() 
{
    Debug.Log("The animation event has happened!");
}

Alternatively, you can just add all your handler code inside the MyEventRaised method which is fine if you just want to do something simple but is a bit of an anti-pattern.

Upvotes: 1

Related Questions