How to use WaitForSeconds?

I have a switch statement that goes into a bunch of different cases. What I want is for stuff to happen in one case for 2 seconds and then switch. Here’s what I’m using to do this:

bool leavestate;
void Update(){
    switch (state) {
    
    	case 1:
        //do stuff
            break;
        case 2:
            leavestate = false;
               //do stuff
           Wait();
           if (leavestate){
              state = 1;
          }
          break;
        }
    }
IEnumerator Wait() {
	yield return new WaitForSeconds (2);
	leavestate = false;
}

Now when state is equal to 2 and it goes into case to, it doesn’t come out of it. It should enter state 2, stay in that state for 2 seconds then enter state 1 but with the above code, it stays in state 2.

You have to call your IEnumerator function.

Like this,

 StartCoroutine(Wait()); 

Not,

Wait();

switch (state)
{

            case 1:
                //do stuff
                break;
            case 2:
                if (!leaveState)
                {
                    StartCoroutine(Wait());
                }
                break;
        }
    }

IEnumerator Wait()
    {
        leaveState = true;
        //do stuff
        yield return new WaitForSeconds(2f);
        state = 1;
    }

of course you need to make sure in the frame that it changes the stages and goes to 2 the leaveStage should be false. You could always use a dedicated bool to see if the coroutine has finished and not the leaveStage one. Now a bit of info why your code doesn’t work, first of all keep in mind that Update is called everyframe so the code in the case will be executed every frame so you need a way to see if the coroutine (Wait()) has finished if not it will keep calling the coroutine and create a new instance of it every frame till the first one is finished quite bad practice. Second the leavestage is set permantly to false so the stage = 1 is never reached, it stacks in there. You should really check around how coroutines work, there several tutorials and articles on the subject. Cheers hope that helps.