Strange delay with "GetCurrentAnimatorStateInfo"

Hello everybody!

I get a very strange delay when I am trying to get the current animator state.

I want to check in my update function if the current animation state is the idle animation. If that is the case, I want to set the animator speed to 1.

When I click the attack button (left mouse button), I want to set the animator speed to the attack speed.

The problem is, when I run the code, the animator doesn’t seem to update the states properly!
When I hit the attack button the animator is still in the idle state for a short amount of time and therefore resets the speed back to 1 before my attack animation had even played.

Here is the code

    void Update()
    {
        if (anim.GetCurrentAnimatorStateInfo(0).IsName("BoneIdleAnim") && anim.speed != 1)
        {
           Debug.Log("reset!");
           anim.speed = 1;
        }

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitpoint;

        Attack();
    }

    void Attack()
    {
        if (Input.GetButtonDown("Fire1") && canAttack)
        {
            Debug.Log("hit");
            anim.speed = attackSpeed;
            canAttack = false;
            anim.SetTrigger("hit");
            Invoke("ResetAttackFlag", rof);
            // source.PlayOneShot(swingSound);
        }
    }

How can I solve this problem?

Greetings from germany,
Lardos

It may be in the transition from Idle to Attack. I often write checks like this with

stateInfo.IsName("MyState") && !anim.IsInTransition()

to make sure that no transitions are currently playing. Alternately you can use a StateMachineBehaviour to detect when you have entered a state, or use a timer to check that some minimum amount of time has passed before exiting the Attack state.

5 Likes

Thank you very much! That fixed my Problem :slight_smile:

You have just saved me!!!