Damge Over Time (AoE) - OnTriggerStay

Hello! I have been stuck with Damage over Time with AoE. I want to make similar skill like “Whirlwind”.
Right now the damage only works on 1 enemy,

    private float timer;
    private float cooldown = 0.5f;

    private void OnTriggerStay(Collider other)
    {
        {
            if(other.tag == "Enemy")
            {
                if (Time.time > timer)
                {

                    timer = Time.time + cooldown;
                    // Damage the enemy
                    other.gameObject.GetComponent<Enemy>().TakingDamage(player.GetComponent<DataStats>().meleeCombat + player.GetComponent<Skills>().skill[3].spellBonus);

                     // Makes heal over time.
                    player.GetComponent<DataStats>().currHealth += 5;
                    Debug.Log(other.gameObject.name);

                }

            }

        }

    }

If I remove the cooldown I can hit all the enemies, but when I add the cooldown just 1 enemy get hit.

Could I make an loop inside the Trigger?

You have a single timer for every entity that’s being hit.

So first OnTriggerStay fires, first entity of overlapped entities is called for, timer is updated with cooldown. All other entities are called, but it’s in a cooldown.

Try adding a dictionary that remembers the entity as it enters and leaves and gives it its own timer.

Also… use CompareTag, not tag ==:

Something like this:

private float cooldown = 0.5f;
private Dictionary<Collider, float> _table = new Dictionary<Collider, float>();

private void OnTriggerEnter(Collider other)
{
    if(other.CompareTag("Enemy") && !_table.ContainsKey(other))
    {
        _table[other] = float.NegativeInfinity;
    }
}

private void OnTriggerStay(Collider other)
{
    float timer;
    if(!_table.TryGetValue(other, out timer)) return; //if not in table, it's not an enemy

    if (Time.time > timer)
    {

        _table[other] = Time.time + cooldown;
        // Damage the enemy
        other.gameObject.GetComponent<Enemy>().TakingDamage(player.GetComponent<DataStats>().meleeCombat + player.GetComponent<Skills>().skill[3].spellBonus);

        // Makes heal over time.
        player.GetComponent<DataStats>().currHealth += 5;
        Debug.Log(other.gameObject.name);

    }

}

This assumes the AOE is going to be destroyed after some period of time, since the colliders are never removed from the table.

If it gets reused, make sure you purge the table of entries before doing so.

1 Like

Hello! Thanks for the answer, going to try that out.

Note, I edited my post with some example code.

1 Like

Wow thanks mate! That did works great, I could not figure that out by my self. Now did you give me some tips that I can use later on other skills.