I have a 2 scripts, one with coroutine, another with event trigger.
When even triggers i start my coroutine.
This is my coroutine
IEnumerator TextRoutine()
{
textReward.SetActive(true);
yield return new WaitForSeconds(3);
textReward.SetActive(false);
}
However if i trigger the event once more, when coroutine is started, it doesnt extend waitforseconds duration. How do i extend waitforeconds, if trigger is triggered again.
However, there isn’t a built-in approach to solve your problem, one solution might be to simulate the WaitForSeconds yield statement with a while loop, and when you trigger your event, you simply increment the duration used by that loop, something like this:
using UnityEngine;
using System.Collections;
public class DynamicWaitCoroutine : MonoBehaviour
{
// Initial delay time, which we’ll modify dynamically.
private float waitTime = 3f;
// Coroutine reference to allow stopping it if needed.
private Coroutine currentCoroutine;
void Start()
{
// Simulate an event trigger to start the coroutine.
TriggerEvent();
}
public void TriggerEvent()
{
if(currentCoroutine == null)
{
// Reset the wait time to its original value.
waitTime = 3f;
// Start the coroutine if it’s not already running.
currentCoroutine = StartCoroutine(TextRoutine());
}
else
{
/*
* Increment the wait time while the coroutine is running.
* Here you specify the increment you would like to have.
*/
waitTime += 1f;
}
}
private IEnumerator TextRoutine()
{
textReward.SetActive(true);
// Wait for the current wait time.
float elapsedTime = 0f;
while(elapsedTime < waitTime)
{
// Check every frame if the wait time changes.
elapsedTime += Time.deltaTime;
// Wait for next frame.
yield return null;
}
textReward.SetActive(false);
}
}