How would you stop audio from flickering

I was scripting this script that would play a sound when you touch it then reset your character. While testing, I discovered a glitch. The audio flickered when you would touch it. Is there a fix?

function onTouch(part) 
	local character = part.Parent:FindFirstChild("Humanoid")
	character.WalkSpeed = 0
	script.Parent.Touchsound:Play()
	wait(2)
	character.Health = 0
end

script.Parent.Touched:connect(onTouch)

The audio flickers because there’s no debounce, Touched gets fired multiple times hence the flickering. Besides a debounce, you should also check if whoever touching does have a humanoid and if that humanoid’s health is greater than 0, to prevent dead people from playing the music again, overall, something like this

local deb = false

function onTouch(part) 
	local hum = part.Parent:FindFirstChild("Humanoid")
	if not hum or hum.Health <= 0 or deb then return end
	deb = true
	hum.WalkSpeed = 0
	script.Parent.Touchsound:Play()
	wait(2)
	hum.Health = 0
	deb = false
end

script.Parent.Touched:Connect(onTouch)
1 Like