Add a damage delay between enemy/player contact hits?

I have a script which will damage the player if he comes into contact with an enemy. Its works, but the problem is if the player doesnt move instantly all his health will be removed as there is no delay between contact hits, and I dont know how I can add a delay?

This is attached to the enemy:

//Weapon Collider Script
  void OnTriggerEnter(Collider hit)
  {

  if (hit.gameObject.tag == "Player")
  {
  hit.GetComponent<PlayerHealth>().TakeDamage(15);

  CameraShake.Shake(0.25f, 0.4f);
  
  }

  }

This code should only happen once when the colliders first overlap. You’re seeing this function get run multiple times per collision?

1 Like

OnTriggerEnter should happen only once per collision. However, you could have the code in the function run only if a bool is true, and then set that bool after some time using an IEnumerator coroutine.

Yes its running continuously once contact is made.

Im not sure how to use coroutines with void OnTriggerEnter? I tried but it messes everything up.

To me that means you have something set up wrong. How are you moving your objects?

Making OnTriggerEnter only do something once is just a bandaid to your real problem. It should only run once per overlap by design, so fix that and your problem is solved.

You can still add a delay on top of that if you want, like this:

public float damageTimeout = 1f;
private bool canTakeDamage = true;

//Weapon Collider Script
private void OnTriggerEnter(Collider hit) {

    if(canTakeDamage && hit.gameObject.tag == "Player") {
        hit.GetComponent<PlayerHealth>().TakeDamage(15);
        CameraShake.Shake(0.25f, 0.4f);

        StartCoroutine(damageTimer());
    }

}

private IEnumerator damageTimer() {
    canTakeDamage = false;
    yield return new WaitForSeconds(damageTimeout);
    canTakeDamage = true;
}

That way even with OnTriggerEnter happening once per contact, you can prevent too many hits in quick succession.

3 Likes

That’s brilliant pal cheers, its working properly now.

I have no idea why it wouldn’t work as it was though. My objects move either by a waypoint system or a simple mover script. I dont think I have anything super fancy running.