- Home /
How do I prevent audio from restarting if it's being asked to play again?
Basically I'm trying to add sound to my fully automatic M4. I have a sound file of a single shot from an M4 which I'm using. I made a script that tells the sound to play every few seconds as long as mouse button 1 is down. The problem is that instead of the sound playing out fully with the new one playing on top of it a few seconds later, the sound just restarts constantly without playing out fully. It works fine only if my weapon is semi auto with a RoF longer than the sound file, but my weapon has a high RoF. Here is the script:
#pragma strict
var gunSmoke : ParticleSystem;
var isFiring = false;
function Update ()
{
if (Input.GetMouseButtonDown(0))
{
isFiring = true;
InvokeRepeating("ShotSound",0,0.3); //This also acts as RoF
gunSmoke.Play();
}
if (Input.GetMouseButtonUp(0))
{
isFiring = false;
CancelInvoke();
gunSmoke.Stop();
}
}
function ShotSound ()
{
if (isFiring == true)
{
audio.Play();
}
}
If you load audioclip and play you will see the behaviour you describe. Try playing it with OneShot ins$$anonymous$$d.
Answer by Simon-Larsen · Jan 26, 2015 at 10:12 PM
You could check if the audio is already playing
if (!audio.isPlaying)
audio.Play();
You may also want to enable the "looping" flag when firing starts and then disable it again when firing stops - only calling Play() between starting and stopping once.
Answer by WerewoofPrime · May 15 at 05:53 PM
https://gamedevbeginner.com/how-to-play-audio-in-unity-with-examples/#clip_at_point
i found this! watch the part of the video about PlayOneShot, it overlaps sounds if one is already playing instead of restarting them :D
Your answer
Follow this Question
Related Questions
Audio loops too early 2 Answers
Sound will not play in an if statement. 1 Answer
Script unattached to Object will not compile 1 Answer
Audio Script 1 Answer
Is there a way to create a random Audiosource loop? 2 Answers