How can I put a debounce in this?

I’m learning scripting and I’m having trouble making the debounce. If you add suggestions/feedback to make it so the debounce works that would be greatly apprieciated.

local part = script.Parent

local debounce = false

local function whenTouched()
	if not debounce then
		
	end
	debounce = true
	local newPart = Instance.new("Part",game.Workspace)
	newPart.Size = Vector3.new(1,1,1)
	newPart.BrickColor = BrickColor.new("Electric blue")
	newPart.Position = Vector3.new(0,0,0)
	newPart.Anchored = false
	debounce = false
end

part.Touched:Connect(whenTouched)


You are sooo close!

local part = script.Parent

local debounce = false

local function whenTouched()
	if not debounce then
	     debounce = true
	     local newPart = Instance.new("Part",game.Workspace)
	     newPart.Size = Vector3.new(1,1,1)
	     newPart.BrickColor = BrickColor.new("Electric blue")
	     newPart.Position = Vector3.new(0,0,0)
	     newPart.Anchored = false
	     debounce = false
	end
end

Try that. Basically, what you have to do, is check if debounce is false. If it is, then set it to true, so it cannot fire again. Then, once you have completed your function, set it back to false, so it can fire again. Hope this helps!

Additional links:

2 Likes
local part = script.Parent

local debounce = false

local function whenTouched()
	if debounce == false then
        debounce = not debounce
        code stuff
        wait(amount of time)
        debounce = false
	end
end

part.Touched:Connect(whenTouched)

so what this does is it checks if debounce is false. If it is, then it executes the code, sets it to true for an amount of time and then sets it to false again

2 Likes

Dang, I was close and thanks for helping me. I didn’t realize that I needed to put the debounce = true inside the if statement.

It worked but it was weird. There were multiple parts spitting out at once? Any way to fix this?

Also, @AmNotPoly I marked yours as a solution but can you also do this?

local part = script.Parent

local debounce = false

local function whenTouched()
	if not debounce then
		debounce = true
		local newPart = Instance.new("Part",game.Workspace)
		newPart.Size = Vector3.new(1,1,1)
		newPart.BrickColor = BrickColor.new("Electric blue")
		newPart.Position = Vector3.new(0,0,0)
		newPart.Anchored = false
		wait(4)
		debounce = false
	end
end

part.Touched:Connect(whenTouched)

That’s exactly the same thing.

debounce = not debounce --(debounce is the opposite of what it was. In this case, true)
--is the same as
debounce = true -- better for predictability
1 Like

Oh ok. Thanks for letting me know!

1 Like