(C#) Attack button not firing due to Update

Hey everyone!


I’m building a player script and have gotten to the “attack” part of my coding. Now, due to the Idle being called every frame, whenever I hit the button to attack, a single frame is being shown before snapping back to the idle/walk state.

EDIT: I’m also currently not using transitions in my animator, all the animations are being called via the script.


Can anyone offer a way to order this code so I can play the full attack animation before going back to idle/walk? It’s probably ridiculously simple but I’ve been frying my brain for the past few days on this and it’s really slowed down production.


Here is my current code:

	private Animator anim;
	private Rigidbody2D rb2d;
	[SerializeField]
	private float speed;




	void Awake()
	{
		rb2d = GetComponent<Rigidbody2D> ();
		anim = GetComponent<Animator> ();
	}

	// Use this for initialization
	void Start () {
		
	}

	void Update()
	{
		if (Input.GetAxisRaw ("Horizontal") != 0 || Input.GetAxisRaw ("Vertical") != 0) 
		{
			Facing ();
			CalculateMovement (new Vector2 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical")));
		} 

		else 
		{
			CalculateMovement (new Vector2 (0, 0));
		}

	    AnimatePlayer ();
	
	}

	void AnimatePlayer()
	{
		if (rb2d.velocity != Vector2.zero) 
		{
			anim.Play ("Movement");
		} 
		else 
		{
			anim.Play ("Idle");
		}

		if(Input.GetButtonDown("Fire1"))
			{
			PlayerAttack ();
			}
	}

	void CalculateMovement(Vector2 movementValue)
	{
		movementValue = movementValue.normalized;
		rb2d.velocity = new Vector2 (movementValue.x * speed * Time.deltaTime, movementValue.y * speed * Time.deltaTime);
	}

	void Facing()
	{
		anim.SetFloat ("DirX", Input.GetAxisRaw("Horizontal"));
		anim.SetFloat ("DirY", Input.GetAxisRaw("Vertical"));
	}

	void PlayerAttack()
	{
		anim.Play ("Attack 1");
	}

}

Please and thank you! :slight_smile:

@Ruff_Demon,
You would do that in the animator…not the code. Check the box “has transition time”, on the transition between the walk and attack animations/states

You could check if attack animation is playing before calling Idle/Walk animation. Try something like this(not tested):

            if(!anim.GetCurrentAnimatorStateInfo(0).IsName("Attack 1"))
            {
                        if (rb2d.velocity != Vector2.zero) 
                        {
                             anim.Play ("Movement");
                        } 
                       else 
                       {
                             anim.Play ("Idle");
                       }
            }