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;
}
}
You can use
IEnumerator
to run time-dependent methods. The method description is as follows:In addition, you need to consider the condition not in timer.