Unity 3D slow motion effect script

by NSDG • Jan 10, 2019 • 0 Comments
156
Altering time pace in Unity 3D is quite easy, all you have to do is change the value of Time.timeScale (1 is default value, anything below that will make the time slower, anything above that will make the time faster).

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 it, but luckily, changing their pitch is enough to simulate a believable slow motion effect.

Below is a simple script that finds all AudioSources in the Scene and activates the slowmotion effect on Key press.

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;
            }
        }
    }
}



  • Simply attach the script above to any GameObject, then press Q in the game to activate/deactivate the slow motion effect.

Pro Tip: To make sure Rigidbodies are simulated smoothly during the slow motion effect, set their Interpolate value to Interpolate or Extrapolate.