Hey guys! First time poster here, Im on a lot of online courses, and i started watching some real simple compounds to just make some pretty basic things. So, basically I have an issue where when i press “i” to attack, the collider triggers and enables to reach out and hit something, then there is a timer that goes down for it to be allowed to be hit again. However, i could press it again and reset that timer essentially creating an almost endless spam of attacks. I am trying to fix this with no luck as Im new and out of ideas!
using System.Collections;
using UnityEngine;
public class PlayerAttack : MonoBehaviour {
private bool attacking = false;
private float attackTimer = 0;
private float attackCd = .35f;
public Collider2D attackTrigger;
private Animator anim;
void Awake() {
anim = gameObject.GetComponent<Animator>();
attackTrigger.enabled = false;
}
void Update() {
if (Input.GetKeyDown("i") && !attacking) {//here is the input for I, which once hit it states attacking is now true. Then start the count down for attack timer. If the attack timer is not 0 then attacking will always be false.
attacking = true;
attackTimer = attackCd;
attackTrigger.enabled = true;
}
if (attacking) {
if (attackTimer > 0) {
attackTimer -= Time.deltaTime;
} else {
attacking = false;
attackTrigger.enabled = false;
}
}
anim.SetBool("Attacking", attacking);// here is the animation which actually plays correctly. the animation goes out and stays out until the timer is done - but the i button is still readable and still re adds the collider over and over.
}
}
Essentially im not sure how to tell the code that the get input for I key, is not possible if that timer is ticking. The animation will go through MOST of the time but often the loop will hold the animation up for a while. What id LIKE is for the animation to play and end, then the timer to go through. I can move the animation request into the input key so it plays directly - but what can i try to stop the trigger from being repeatable during the timer? If you need anymore information let me know ![]()
edit: Managed to solve this on my own. For the first issue being that it needed to have (Input.GetKeyDown(“i”) && !attacking) - also add && attackTimer <= 0. This way it also cant be effected unless coold down is at 0. The next step was fixing the animation - well there was a option for “has exit time” when i turned off the has exit time it seemed to have fixed the issue. Going to research later tonight what that even means. Also changed (“i”) to KeyCode.I after the first reply - looked into it and its the same function but seems cleaner and allows me to auto input through VS.