Cant stop attack animation once clicking button.

I dont know what is going on here. It seems like a pretty simple problem but I cant figure it out myself. I set my char to attack when pressing left mouse button, somehow it keeps non-stopped attacking. Can anybody help me :frowning: It already took me half a day. Here’s my script. Thank you in advance :frowning:

using UnityEngine;
using System.Collections;

public class KnightController : MonoBehaviour {
	
	public float speed = 10;
	public float rotationSpeed = 30;
	public float animSpeed = 1.5f;
	
	private GameObject player;
	private Animator anim;
	private AnimatorStateInfo currentBaseState;
	private HashIDs hash;
	private float cdLeftAtk = 1;
	private float timeReset = 0;
	
	void Awake () {
		player = GameObject.FindGameObjectWithTag(Tags.player);
		anim = player.GetComponent<Animator>();
		anim.speed = animSpeed;
		hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<HashIDs>();
		currentBaseState = anim.GetCurrentAnimatorStateInfo(0);
	}
	
	void FixedUpdate () {
		float h = Input.GetAxis("Horizontal");
		float v = Input.GetAxis("Vertical");
		
		anim.SetFloat("speed", v);
		transform.Translate(0,0, v * speed * Time.deltaTime);
		transform.Rotate(0, h * rotationSpeed * Time.deltaTime, 0);
		if(timeReset > 0)
			timeReset -= Time.deltaTime;
		else if (timeReset < 0)
			timeReset = 0;
		
		if(Input.GetMouseButtonUp(0))
		{
			Debug.Log(timeReset);
			if(timeReset == 0)
			{
				anim.SetBool("LeftClick", true);
				timeReset = cdLeftAtk;
				if(currentBaseState.nameHash != hash.leftAttackState)
				{
					anim.SetFloat("attackparameter", Random.Range(1.0f, 4.0f));
				}
				else
				{
					anim.SetBool("LeftClick", false);
						
				}

			}

		}
	}
}
 void FixedUpdate () {
    ...
    if(Input.GetMouseButtonUp(0)) {

Input.GetMouseButtonUp(0) is only going to be true once, when you unclick the mouse. So you’ll never get to anim.SetBool(“LeftClick”, false);

Perhaps you could use something like:

anim.SetBool("LeftClick", Input.GetMouseButton(0));

This guarantees that the LeftClick parameter is always true when the mouse button is down, and always false when the mouse button is up.

1 Like

Much appreciate this :smile: though there’re still somes minor bugs but it helps me find a way. Tks again :slight_smile:

This thread has a play one shot little script that works nicely -
http://forum.unity3d.com/threads/165093-How-to-play-an-animation-only-once-using-Mecanim

1 Like

I’ll try it. Thank you :slight_smile: