Want health to decrement longer stays on trigger

When OnTriggerEnter event is fired then health decrements by 5.
Now I want it to check every so many seconds and if still there then decrement another 5.

I had absolutely no success with OnTriggerStay so OnTriggerEnter sets a bool to true and OnTriggerExit sets to false.

What I want is while true it will decrement but obviously not on Update.

I have tried calling a coroutine with a yield in which waits the first time, and then decrements on every update so I am obviously not calling it correctly

The Coroutine is simply this

IEnumerator OnSpikes()
{    
     
     audio.PlayOneShot(spikesSound);
     yield return new WaitForSeconds(5.0f);
     health -=1;
}

I have tried calling the coroutine from all over the place (can’t even remember them all) and in while loops
Anyway, can someone lead me in the right direction
(I have searched and searched and tried all sorts of things but I’m obviously missing something)

thanks in advance

}

Greetings,

If you call StartCoroutine before the previous one has ended, this error will occur. My advice is to set a boolean to “true” in OnTriggerEnter (or wherever), then during Update() launch your Coroutine if the boolean is “true”. The end of the Coroutine will then set this boolean to “false”.

See the answer here for an example: coroutine for reloading - Questions & Answers - Unity Discussions

-Kevin

Try something like this:

private bool isInTrigger = false;

void Start()
{
    StartCoroutine(OnSpikes());
}   

void OnTriggerEnter(Collider other)
{
    isInTrigger = true;
}

void OnTriggerExit(Collider other)
{
    isInTrigger = false;
}

IEnumerator OnSpikes()
{    
    while (true)
    {
        if (isInTrigger)
        {
            audio.PlayOneShot(spikesSound);
            health -=1;     
        }
        
        yield return new WaitForSeconds(5.0f);          
    }
}