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

How Do You Add Debounce In This Script?

How do you add debounce in this script? I want it to wait 4 seconds before it does the second part of the coding when touched. So, it does the first action, then wait 4 seconds, next do the second action, and at last wait another 4 seconds before it does the first action again. Thanks!

local boolean = false

function onTouched()
    if boolean then
        boolean = false
--code
wait(4)
    else
        boolean = true
--code
wait(4)
    end
end


script.Parent.Touched:connect(onTouched)

2 answers

✓ Accepted answer
local boolean = true
local action = 1

function onTouched()
	if boolean == true then
		boolean = false
		if action == 1 then
			action = 2
				--action1
			wait(4)
			boolean = true
		elseif action == 2 then
			action = 1
				--action2
			wait(4)
			boolean = true
		end
	end
end

script.Parent.Touched:connect(onTouched)

7 comments

0

Sorry but I need it to do the second action, I think this only does 1 action

0

What do you mean?

0

Is that what you mean?

0

Sorry that I am not clear xD I mean like when it is touched the first time, it does something. Then when it is touched the second time, it does a different action.

0

Okay, I think I got it this time

0

Thanks it worked! I have two questions, but it is not necessary to answer them, you can just ignore them if you want. Is boolean still nessesary ? Also, is there an official word to replace "action"?

0

Boolean is the debounce, you can rename it to whatever you like, as for your second question, I don't know. Maybe scope? I'm still new to scripting myself.

Something like this should work.

local boolean = false

function onTouched()
    if not boolean then
	boolean = true
	wait(4)
	--run your code
	boolean = false
end


script.Parent.Touched:connect(onTouched)

Here's a practical use for debounce.

local debounce = false
script.Parent.Touched:connect(function(hit)
	if not debounce then
		debounce = true
		local hit = hit.Parent
		local hum = hit:FindFirstChild("Humanoid")
		hum.Health = hum.Health - 5
		wait(3)
		debounce = false
	end
end)

2 comments

0

Sorry but I need it to do the second action, I think this only does 1 action. In my script there is 2 coding parts. I need it to do the first action, wait and then do the second action

0

Can you post your code? It's kind of hard to answer your request if we're not sure what you're doing.

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