How to create a slow motion effect in Unity and C#

I was following a Brackeys tutorial (credit where is due) in order to get back to speed with Unity after a long hiatus and he showed a kind of matrix-effect on game over that can be applied to multiple situations, so I decided to play with it and use it in my future (if any) games. This is how it looks like after a quick prototype re-using Longanizers concept art:

Adding a slow motion effect when our character dies

To start we’ll need to declare some variables to play with time:

// We'll declare a variable to store the slowness factor:
public float slowness = 10f;
// If 1 is regular time, we can use 1/x to make the time slower than regular time: 
Time.timescale = 1f / slowness;
// In this specific project I use FixedUpdate() frame-rate, so we'll also alter the time using fixedDeltaTime:
Time.fixedDeltaTime = Time.fixedDeltaTime / slowness; 

We use a Coroutine in order to stop the method execution until a new order is given:

// The time is already stopped at this moment, so if we only use 1f it will not be 1 second, but 10, we need to divide this by the slowness factor:
yield return new WaitForSeconds(1f / slowness); 

We cannot forget to restore the time to regular time after our action has been completed:

// Restores time to its normal state:
Time.timeScale = 1f;
Time.fixedDeltaTime = Time.fixedDeltaTime;

Full code:

    public float slowness = 10f;

    public void EndGame()
    {
        StartCoroutine(RestartLevel());
    }

    IEnumerator RestartLevel()
    {
        Time.timeScale = 1f / slowness;
        Time.fixedDeltaTime = Time.fixedDeltaTime / slowness;

        yield return new WaitForSeconds(1f / slowness);

        Time.timeScale = 1f;
        Time.fixedDeltaTime = Time.fixedDeltaTime; 
    }

Comments

Leave a Reply

%d bloggers like this: