Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Script overlaps sound playing on localscript?

I made a script where when a player touches a part, it is intended to play a sound singularly and loops. However, when I play the sound, the music plays repeatedly, as long as the humanoid collides with the part.

How do I configure the script so that it will play the sound only once, and loop?

script.Parent.Touched:connect(function(hit)
local find = hit.Parent:FindFirstChild("Humanoid")
if find ~= nil then
local sound = script.Parent.Sound1:Clone()
sound.Parent = hit.Parent
sound:Play()
	wait(TimeLength)
end
end
end)

1 answer

Well, to prevent the script from running again we can add a debounce or destroy the script all together if you don't want anyone else using it.

A debounce ussally involves a bool value and checking it when the function starts, then changing it to false so it won't run.

first we start by setting the variable

local debounce = true

then we check if the debounce is true

if debounce==true then

then we set it to false so it only runs once

debounce=false

then at the end of the script we can either destroy the script or set debounce back to true

debounce=true

If we do all these we get this script/

WITH DEBOUNCE This script will wait 5 seconds before being able to use it again set by TimeToWait.

local debounce=true
local TimeToWait = 5

script.Parent.Touched:connect(function(hit)
if debounce==true then
local find = hit.Parent:FindFirstChild("Humanoid")
if find ~= nil then
local sound = script.Parent.Sound1:Clone()
sound.Parent = hit.Parent
sound:Play()
    wait(TimeToWait )
end
end
end
end)

OR

DESTROY SCRIPT this will destroy the script all together only doing it once

script.Parent.Touched:connect(function(hit)
if debounce==true then
local find = hit.Parent:FindFirstChild("Humanoid")
if find ~= nil then
local sound = script.Parent.Sound1:Clone()
sound.Parent = hit.Parent
sound:Play()
script:Destroy()
end
end
end
end)

hoped this helped :)

This discussion is preserved as it was. New answers, comments, and votes are closed.