- Home /
How to make a sound play and have a delay after so it can't be activated again very fast?
Hello. I want my sounds to have a delay after they are played so you can't activate them again very fast. I want to do this to my collision sounds because if a player walks into an object for a longer time the sound keeps playing because it detects a new collision and it is very annoying. I want to add a second of delay (or cooldown, how you want to name it) and then the sound can be activated again.
Thanks to all who will help :D
Answer by The_Three_Vs · Aug 06, 2020 at 12:41 AM
You can make a cooldown by using a coroutine and a boolean that tells whether the coroutine cooldown is running. For example:
public float cooldownTime = 1f;
private bool inCooldown;
private IEnumerator Cooldown()
{
//Set the cooldown flag to true, wait for the cooldown time to pass, then turn the flag to false
inCooldown = true;
yield return new WaitForSeconds(cooldownTime);
inCooldown = false;
}
private void OnCollisionEnter(Collision collision)
{
//If the Cooldown coroutine is not currently running, play the sound and start a new cooldown
if(!inCooldown)
{
//Play sound
StartCoroutine(Cooldown());
}
}
Hope this helps!
Your answer
Follow this Question
Related Questions
Portal Sound start AFTER the Teleportation 0 Answers
Dice roll collision sound 1 Answer
Delay between clicks and sound 2 Answers
How can I add time to a timer on an object collision? 1 Answer
Delay Jumping 3 Answers