Search code examples
unity-game-enginedelayyieldcoroutineienumerator

How do i get unity to wait until my animation is done


I'm working on a unity project and I want too switch between scenes with an fade in and fade out animation. The animation are done and I can access them but I'm working with yield and Ienumerator functions from a tutorial but I can't get it to work.

//from my animation script
public IEnumerator fadeIn()
{
    isFading = true;
    animator.SetTrigger("FadeIn");
    while (isFading)
    {
        yield return new WaitForSeconds(3f);
    }
}

// from my main menu script.
public void btnPlay()
{
    StartCoroutine(fadeIn());
    Debug.Log("AfterIn");
    SceneManager.LoadScene("playOptions");
    StartCoroutine(fadeOut());
    Debug.Log("AfterOut");
}

IEnumerator fadeIn()
{
    yield return StartCoroutine(animatorscript.fadeIn());
}
IEnumerator fadeOut()
{
    yield return StartCoroutine(animatorscript.fadeOut());
}

I've updated my question. But when I run it i see no animation. It goos direct to the next scene and de debug messages direct after each other.


Solution

  • When you want to start a Coroutine you need to call it like this StartCoroutine(fadeIn) the same way you are doing yield return StartCoroutine(animatorscript.fadeIn()).

    So you need to append

    public void btnPlay()
    {
        StartCoroutine(fadeIn);
        SceneManager.LoadScene("playOptions");
        StartCoroutine(fadeOut);
    }
    

    See here for more information on StartCoroutine

    UPDATE: In regards to your updated question, I assume you wish to wait until the fadein finishes to load the scene.

    Something like this would do the trick;

    public void btnPlay()
    {
        StartCoroutine(SceneFadeAndLoad);
    }
    
    IEnumerator SceneFadeAndLoad()
    {
        yield return StartCoroutine(fadeIn);
        SceneManager.LoadScene("playOptions");
        yield return StartCoroutine(fadeOut);
    }