简体   繁体   中英

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.

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.

创建动画事件

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

注册事件处理程序

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

添加动画事件处理脚本

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM