Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Strange delay with "GetCurrentAnimatorStateInfo"

Discussion in 'Animation' started by Lardos, Dec 5, 2017.

  1. Lardos

    Lardos

    Joined:
    Mar 5, 2015
    Posts:
    8
    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

    Code (CSharp):
    1.     void Update()
    2.     {
    3.         if (anim.GetCurrentAnimatorStateInfo(0).IsName("BoneIdleAnim") && anim.speed != 1)
    4.         {
    5.            Debug.Log("reset!");
    6.            anim.speed = 1;
    7.         }
    8.  
    9.         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    10.         RaycastHit hitpoint;
    11.  
    12.         Attack();
    13.     }
    14.  
    15.     void Attack()
    16.     {
    17.         if (Input.GetButtonDown("Fire1") && canAttack)
    18.         {
    19.             Debug.Log("hit");
    20.             anim.speed = attackSpeed;
    21.             canAttack = false;
    22.             anim.SetTrigger("hit");
    23.             Invoke("ResetAttackFlag", rof);
    24.             // source.PlayOneShot(swingSound);
    25.         }
    26.     }
    How can I solve this problem?

    Greetings from germany,
    Lardos
     
  2. joebain

    joebain

    Joined:
    Oct 24, 2014
    Posts:
    47
    It may be in the transition from Idle to Attack. I often write checks like this with

    Code (csharp):
    1. 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.
     
  3. Lardos

    Lardos

    Joined:
    Mar 5, 2015
    Posts:
    8
    Thank you very much! That fixed my Problem :)
     
  4. Marquetes2

    Marquetes2

    Joined:
    Aug 29, 2018
    Posts:
    3
    You have just saved me!!!