So I have an OnTriggerEnter function that removes health every second usig a Coroutine. I want to stop it with a OnTriggerExit function and StopCoroutine. While this works with only one gameObject, it breaks with multiple colliders since it always cancels "routine". What would be the best way to stop just the Coroutine for the object that left the Collider? I feel like there is an easy solution for it but I just don't see it.
OnTriggerEnter/Exit
private float delay= 1f;
void OnTriggerEnter(Collider other)
{
DealDamage(other, delay);
}
private void OnTriggerExit(Collider other)
{
StopDamage();
}
Coroutine
private Coroutine routine;
private void DealDamage(Collider col, float damageRate)
{
var health = col.GetComponent<IChangeHealth>();
if (health == null) return;
routine = StartCoroutine((DamageEverySecond(health, damageRate)));
}
IEnumerator DamageEverySecond(IChangeHealth health, float rate)
{
while (true)
{
health.RemoveHealth(Damage);
yield return new WaitForSeconds(rate);
}
}
protected void StopDamage()
{
StopCoroutine(routine);
}