- Home /
Hello there!! So when i hold LMB its continuously makes the gun noise but i want it so that there a 2 second delay in between each gun sound, how do i do this??
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class GunShot : MonoBehaviour
{
public AudioSource someSound;
void Update()
{
if(Input.GetButton("Fire1"))
{
someSound.Play();
}
}
},using System.Collections;
using System.Collections.Generic; using UnityEngine;
public class GunShot : MonoBehaviour {
public AudioSource someSound;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetButton("Fire1"))
{
someSound.Play();
}
}
}
Answer by nutraj · Aug 03, 2020 at 12:48 PM
It's pretty simple, actually. You could just use a recursive co-routine to achieve this. And, we will also use a boolean to check if the button is being pressed or not.
So your updated script would look like this :
public class GunShot : MonoBehaviour {
public AudioSource someSound;
private bool isButtonPressed = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetButton("Fire1"))
{
// Check if we are already playing the gunsound...
if (isButtonPressed == false)
{
isButtonPressed = true;
StartCoroutine(PlayGunSound());
}
}
else
{
isButtonPressed = false;
}
}
}
IEnumerator PlayGunSound()
{
someSound.Play();
// wait for 2 seconds
yield return new WaitForSeconds(2f);
// Play the gunshot sound again if the button is still being pressed
if (isButtonPressed)
{
StartCoroutine(PlayGunSound());
}
else
{
// Do nothing !
}
}
}
Let me know how it turns out for you :)
Your answer
Follow this Question
Related Questions
Automatic repeated sound 1 Answer
Unity and music tracks - load track at certain point and fading tracks in and out 1 Answer
Breathing sound effect using timers 1 Answer
How do I add a gunshot sound to this? 2 Answers
How to make a sound play and have a delay after so it can't be activated again very fast? 1 Answer