Continuous Attack Damage to Enemy [HELP]
Hi! I'm new to Unity and while I was making a player attack script (which works), I notice if I accidentally hold my attack key (mouse 0) instead of clicking it once, instead of a one-time hit damage, the player damage to the enemy would be continuous until you let go of the attack key.
I'm not so sure how to counter this, I was thinking about putting a one second time limit on the player damage to the enemy or some sort of cooldown to the damage I can inflict. Any tips?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerCombat : MonoBehaviour
{
public Animator animator;
public Transform AttackPoint;
public float AttackRange;
public LayerMask Enemy;
public int AttackDamage;
public float AttackRate;
float NextAttackTime = 0f;
// Start is called before the first frame update
void Update()
{
if(Time.time >= NextAttackTime)
{
if (Input.GetButton("Mouse X"))
{
animator.SetTrigger("Attack");
Attack();
NextAttackTime = Time.time + 3f / AttackRate;
}
}
}
void Attack()
{
//Detect Enemies
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(AttackPoint.position, AttackRange, Enemy);
//Damage Enemies
foreach(Collider2D Enemy in hitEnemies)
{
Debug.Log("Enemy hit");
Enemy.GetComponent<enemyHealthSystem>().TakeDamage(AttackDamage);
}
}
void OnDrawGizmosSelected()
{
if (AttackPoint == null)
{
return;
}
Gizmos.DrawWireSphere(AttackPoint.position, AttackRange);
}
}
Comment