Slowmotion time limit

130 views Asked by At

I made a player in my game, such that it goes into slow-motion when you hold down the space bar. But I want the player to only be available to be in slow-motion for 5 seconds at a time. After 10 seconds the player will be available to go into slow-motion again.

Here is the code for the script

using UnityEngine;

public class SlowMotion : MonoBehaviour
{
    public float slowMotionTimescale;

    private float startTimescale;
    private float startFixedDeltaTime;

    void Start()
    {
        startTimescale = Time.timeScale;
        startFixedDeltaTime = Time.fixedDeltaTime;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            StartSlowMotion();
        }

        if (Input.GetKeyUp(KeyCode.Space))
        {
            StopSlowMotion();
        }
    
    }

    private void StartSlowMotion()
    {
        Time.timeScale = slowMotionTimescale;
        Time.fixedDeltaTime = startFixedDeltaTime * slowMotionTimescale;
    }

    private void StopSlowMotion()
    {
        Time.timeScale = startTimescale;
        Time.fixedDeltaTime = startFixedDeltaTime;
    }
}
1

There are 1 answers

0
KiynL On BEST ANSWER

You can use IEnumerator to run time-dependent methods. The method description is as follows:

public bool inTimer; // are slow motion is in timer?
public IEnumerator StartTimer()
{
    inTimer = true;
    
    StartSlowMotion();
    
    yield return new WaitForSeconds(5f); // wait to end slow motion

    StopSlowMotion();
    
    yield return new WaitForSeconds(5f); // wait time to finish
    
    inTimer = false;
}

In addition, you need to consider the condition not in timer.

if (Input.GetKeyDown(KeyCode.Space) && !inTimer)
{
    StartCoroutine(StartTimer()); // how to run timer
}