Unity Slow Motion
Altering the time pace in Unity is quite easy, all you need to do is change the value of Time.timeScale.
Time.timeScale is a value in Unity that controls time-dependent events, such as Update functions, animations, particles, physics, etc. When the timeScale is 1, time passes as fast as real-time, with 0.5 time passes 2 times slower than real-time, and with 2.0 the time passes twice as fast. Time.timeScale with the value of 0 pauses any framerate dependent calculations, negative values are ignored.
However, just by setting the value of timeScale is not enough to make a believable slow-motion effect.
Some components such as AudioSource are not affected by time, but luckily, changing their pitch is enough to add a slow-motion effect to the audio.
To make a slow-motion effect in the Unity game, we will need to write a script that will change the value of Time.timeScale and will change the pitch of all active Audio Sources.
Slow-motion is the inverse of fast motion and is the process of slowing down the game speed.
- Create a new script, call it ‘SC_SlowMotionEffect’, remove everything from it then paste the code below inside it:
SC_SlowMotionEffect.cs
using UnityEngine;
public class SC_SlowMotionEffect : MonoBehaviour
{
public float slowMotionTimeScale = 0.5f;
public bool slowMotionEnabled = false;
[System.Serializable]
public class AudioSourceData
{
public AudioSource audioSource;
public float defaultPitch;
}
AudioSourceData[] audioSources;
// Start is called before the first frame update
void Start()
{
//Find all AudioSources in the Scene and save their default pitch values
AudioSource[] audios = FindObjectsOfType<AudioSource>();
audioSources = new AudioSourceData[audios.Length];
for (int i = 0; i < audios.Length; i++)
{
AudioSourceData tmpData = new AudioSourceData();
tmpData.audioSource = audios[i];
tmpData.defaultPitch = audios[i].pitch;
audioSources[i] = tmpData;
}
SlowMotionEffect(slowMotionEnabled);
}
// Update is called once per frame
void Update()
{
//Activate/Deactivate slow motion on key press
if (Input.GetKeyDown(KeyCode.Q))
{
slowMotionEnabled = !slowMotionEnabled;
SlowMotionEffect(slowMotionEnabled);
}
}
void SlowMotionEffect(bool enabled)
{
Time.timeScale = enabled ? slowMotionTimeScale : 1;
for (int i = 0; i < audioSources.Length; i++)
{
if (audioSources[i].audioSource)
{
audioSources[i].audioSource.pitch = audioSources[i].defaultPitch * Time.timeScale;
}
}
}
}
![](https://sharpcoderblog.com/public/images/b09/b0959d9d13b886c7feb31fcf004fe046.png)
- Attach the script above to any GameObject then press ‘Q’ in the game to activate/deactivate the slow-motion effect.
To make sure Rigidbodies are simulated smoothly during the slow-motion effect, set their Interpolate value to Interpolate or Extrapolate.