Need help with Coroutine

Hey guys,
I want the time to gradually slow down. I have this code but it happens instantaneously.

    IEnumerator Slowspeed(float fadeSpeed)
    {
        float realtime = 1;
        _timeshift = Mathf.Clamp01(_timeshift);
        while(Time.timeScale >= 0.2)
        {
            _timeshift -= realtime * fadeSpeed * Time.deltaTime;
            Time.timeScale = _timeshift;
            Debug.Log (_timeshift);
        }
        yield return null;
    }

and I start the coroutine when the player dies:

    void GameOver()
    {
        Player.alive = false;
        Player._anim.SetBool("IsRunning", false);
        _player.transform.Rotate(0,0,90);
        Instantiate(_deathParticle,_player.transform.position,Quaternion.identity);
        _restartButton.SetActive(true);
        deathText.EnableText();
        spawn.StopSpawning();
       // Time.timeScale = 0.2f;
        StartCoroutine (Slowspeed(0.5f));
        StatManager.death -= GameOver;
    }

A “yield return null” means the coroutine should wait one frame before continuing. You don’t have any yield statements inside your “while” loop, so it will start, loop several times, and finish all in a single frame. I recommend putting a “yield return null” in your while loop so it only loops once per frame.

5 Likes

Awesome! thanks Gambit