Hello there,
I have some difficulties executing a Collision2D trigger event only once. For a top-down 2D game with melee fight, I am using a Capsule Collider 2D for dealing damage to the enemy. Whenever the attack key (‘Space’) is pressed, the Capsule Collider2D attached to the player is activated and any enemy within the range of this collider is damaged.
Now this part of the script works fine. The problem is, that when the OnTriggerEnter2D event is triggered, it should be executed only once and decrease enemy health by 1. The code in the script looks like this:
public class enemyControl : MonoBehaviour {
public int enemyHealth = 3;
public GameObject enemy;
public SpriteRenderer enemySprite;
public Sprite enemyDead;
public Collider2D enemyCollider;
public Collider2D damageCollider;
public Collider2D playerAttack;
void OnTriggerEnter2D (Collider2D playerAttack) {
if (playerAttack.tag == "plrAttack") {
enemyHealth-=1;
}
}
void Start () {
enemySprite = GetComponent<SpriteRenderer> ();
}
void Update () {
if (enemyHealth <= 0)
{
enemySprite.sprite = enemyDead;
enemyCollider.enabled = false;
}
}
}
The problem is that whenever I press the attack key (‘Space’), the collision trigger starts a very fast loop that decreases the enemy’s health to zero immediately. Is there some way to break this “loop” after only one execution?
I have to add, that I have searched the forum for possible solutions, including using OnTriggerExit and introducing a boolean value for checking the state of the trigger, but none of that seemed to work as the loop just goes on.
The attack action script looks like this, btw.:
if (Input.GetKey (KeyCode.Space) && !moving) {
playerAnimator.SetBool ("isAttacking", true);
attack.enabled = true;
fighting = true;
}
“attack.enabled = true” is the row that enables the Capsule Collider 2D that is dealing the damage.
I would really appreciate any help or hints as I am stuck with this unnerving problem for days…
Many thanks!