Problem with WaitForSeconds

I am attempting to make my code wait. I’m having it set a canvas as active then wait 5 seconds and turn it off. I’m trying to use WaitForSeconds but it isn’t working.
This is my code. It’s in an OnTriggerEnter2D function and the second part is another function. waitTime is a float variable.
if (talkedToBront == false && talkedToDimitri == false)
{
errorCanvas.gameObject.SetActive(true);
speed = 0;
errorText.text = “Talk To Bront And Dimitri Before You Leave”;
OptionOneWait();
speed = setSpeed;
errorCanvas.gameObject.SetActive(false);
transform.Translate(-.5f, .5f, 0f);

}

public IEnumerator OptionOneWait()
{
yield return new WaitForSeconds(waitTime);

}

This is a common mistake… people think that calling an IEnumerator/coroutine that waits will return the execution after a time to where it was called. That is not how it works.
All of the code in the coroutine will run, up until the first yield, and then all of the code in your calling method will execute after that.

Move the code below the call to start the coroutine to inside the coroutine, after the yield and try that. :slight_smile:

if (talkedToBront == false && talkedToDimitri == false)
{
  StartCoroutine(OptionOneWait());
}

public IEnumerator OptionOneWait()
{
  errorCanvas.gameObject.SetActive(true);
  speed = 0;
  errorText.text = "Talk To Bront And Dimitri Before You Leave";
 
  yield return new WaitForSeconds(waitTime);
 
  speed = setSpeed;
  errorCanvas.gameObject.SetActive(false);
  transform.Translate(-.5f, .5f, 0f);
}

Or something like this.

https://docs.unity3d.com/ScriptReference/WaitForSeconds.html