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

How can I prevent this?

I am writing a script, that triggers when the player steps on something. I set this up to test if it would work.

local touching = false
script.Parent.Trigger.Touched:connect(function(hit)
	if not touching then
		print("Touched")
		touching = true
	end
end)
script.Parent.Trigger.TouchEnded:connect(function(hit)
	if touching then
		print("TouchEnded")
		touching = false
	end
end)

As a player walks on it, it triggers it multiple times EG, my output window TouchEnded Touched TouchEnded Touched TouchEnded Touched TouchEnded

How can I prevent this from happening?

1 comment

0

On touchended you set the variable back to false, so it can run again:o

1 answer

Use a Debounce. A Debounce prevents the event to happen infinite times.

touching = false --Local not necessary
debounce = true
script.Parent.Trigger.Touched:connect(function(hit)
    if not touching and debounce == true then
        print("Touched")
        touching = true
	debounce = false
	wait(1)
    end
end)
script.Parent.Trigger.TouchEnded:connect(function(hit)
    if touching and debounce == true then
        print("TouchEnded")
        touching = false
	debounce = false
	wait(1)
	debounce = true
    end
end)

1 comment

0

You didn't set debounce to true in the first one. Fix this. xD And local IS necessary. It loads variables quicker, and it's nicer formatting.

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