As the title says, I am trying to find a way of stopping audio from constantly repeating itself inside of loops. The reason why I am trying to make a NPC that fires its minigun at players in a certain radius. A way I am doing this is by using a spawn() function with a while task.wait() do inside of the spawn() which constantly loops through the current players in the game in the game and revs up their minigun when a player enters their radius.
The only way I found by stopping audio from repeating itself during loops is using a boolen, although I don’t like using a boolen to stop this issue is because it feels unprofessional and lazy. So what’s a better way of solving my issue?
I don’t think there is really a better way to do this to be honest, unless you play the audio before the loop is created. Regardless of what you do inside of the loop, you’re still going to have to use an if statement to check if the sound is played. But if you can in your case, play the sound before you start the loop.
Good luck!
A common way to remove branching code is to only work on data you know is valid. For example you could avoid it by only iterating over inactive NPCs. You’re still going to have a radius check but the difference is that filtering stuff out ahead of time lets you separate logic from data.
Hello, you can try playing the sound whenever the .playing property of the sound object is false. This way the sound will only play if it isn’t already playing.
while task.wait() do
if not script.Parent["Name of the Sound"] then
local sound = Instance.new("Sound")
sound.Name = "Name of the Sound"
sound.Parent = script.Parent --[[where should the sound be parented to?]]
sound.SoundId = "rbxassetid://xxxxxxxxxx"
sound:Play()
Debris:AddItem(sound, sound.TimeLength)
end
end