Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question WaitForSeconds() not working.

Discussion in 'Scripting' started by gamer_072008, Jul 23, 2021.

  1. gamer_072008

    gamer_072008

    Joined:
    Apr 6, 2021
    Posts:
    1
    Hi, i am making a game with a cube and a maze. When on the playbutton pressed will the game start a IEnumerator with WaitForSeconds, but it is not working.
    If i remove the WaitForSecond the code works perfectly until the next WaitForSecond (i use multiple).

    So the code works like this:
    A public void will start when on the playbotton is pressed, that void will do some codes and will start a coroutine (IEnumerator) with the function StartCoroutine(), the coroutine starts until the first WaitForSeconds (BTW the first WaitForSecond is the first command in the coroutine, but if i remove it the coroutine just works).

    --My code:

    IEnumerator PlayMovingWallAnimation()
    {
    Debug.Log("Wait 5 seconds");

    yield return new WaitForSeconds(5); // Stops here!

    Debug.Log("Play movingWallSoundEffect and movingWallAnimation");

    movingWallSoundEffect.Play();
    movingWallAnimation.Play("MovingWallAnimation");

    Debug.Log("MovingWallSoundEffect and movingWallAnimation played");

    Debug.Log("Wait 1 second");

    yield return new WaitForSeconds(1);

    Debug.Log("Set isInGame to true");

    isInGame = true;

    Debug.Log("isInGame set to true");

    }
    public void PlayGame()
    {
    Debug.Log("Game started");

    StartCoroutine(PlayMovingWallAnimation());

    quitGameConfirmScreenGameObject.SetActive(false);

    introGuiGameObject.SetActive(false);

    inGameCameraOneGameObject.SetActive(true);

    introCameraGameObject.SetActive(false);
    }

    --End of script.
    (This is not the whole script, the other code does not interact with this code!)

    The PlayGame() void is started when pressed on the playbutton.

    Is there anyone that can help me?

    The uploaded file is the whole script.
     

    Attached Files:

  2. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,091
    Nones going to read your code without code tags. Learn how to use them.
    upload_2021-7-23_20-5-45.png

    Are you by any chance disabling the game object or its parent?
    Doing so will kill the coroutine.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,517
    Yes, get your code tags in.

    Remember that 100% of
    PlayGame()
    executes. It does NOT wait for that coroutine because a) it's not a coroutine itself, and b) you're not yield-ing it even if it was.