Debounce on touch functions

How can I add a debounce on this script?

amnt = math.random(1,5) --how much you get for it
function onTouched(part)
	script.Parent.Transparency = 1
	script.Sound.Playing = true
	script.Parent.Shine.Rate = 0
	
	local invisiblePart = Instance.new("Part")
	invisiblePart.Parent = workspace
	invisiblePart.Anchored = true
	invisiblePart.Position = Vector3.new(-9.5, 2.5, -1.2)
	invisiblePart.Size = Vector3.new(3, 0.4, 3)
	invisiblePart.Transparency = 1
	invisiblePart.CanCollide = false
	local Burst = game.ServerStorage.PowerUpParticles.Bubble:Clone()
	Burst.Parent = invisiblePart
	
	local h = part.Parent:findFirstChild("Humanoid")
	if (h~=nil) then
		local thisplr = game.Players:findFirstChild(h.Parent.Name)
		if (thisplr~=nil) then
			local stats = thisplr:findFirstChild("leaderstats")
			if (stats~=nil) then
				local score = stats:findFirstChild("Smackbux")
				if (score~=nil) then
					score.Value = score.Value + amnt
				end
			end
		end
		wait(3)
		script.Parent:remove()
	end
end

script.Parent.Touched:connect(onTouched)

It’s a coin, but when i collect it, there will be millions of parts and millions of leaderstats i get out of it, in other words, i touch it unlimited times.

It’s simple:

local debounce = true -- your debounce
local cooldown = -- cooldown

function onTouched(hit)
   if not debounce then return end -- if the denounce is false, then simply stop the function.
   debounce = false
   -- rest of code
   wait(cooldown)
   denounce = true
end

But in your case, where you’re destroying the part after the player touches it:

Events return a RBXScriptConnection which when disconnected, stops the event from firing.

An example would be:

local connection
 
connection = script.Parent.Touched:Connect(function(hit)
    if connection then -- if the connection exists.
        connection:Disconnect() -- disconnect it so that other events won't fire.
    end
    print("Oh! This will only be printed once.")
end)
2 Likes