So lets say I want to make a part that when touched prints "Hi" in the output, like this:
local part = game.Workspace.Part
part.Touched:Connect(function() print("Hi") end)
This would work but it would print "Hi" multiple times. So how can I script it so that when it is hit it will print "Hi" but only once? Also how could I deactivate it so that if you walk over it again it wont work. I'm a beginner so any help will be appreciated, thanks!
What you need to do is disconnect the function once it is called to it would only output "Hi" once. To do this, assign the event to a variable, and once the event is triggered, disconnect it.
local Part = workspace.Part local connection connection = Part.Touched:Connect(function(hit) print("Hi") connection:Disconnect() end)
You could use a debounce!
A debounce is essentially a set of code which keeps a function from running too many times, and this problem ironically occurs the most with the .Touched
event. I'll give you an example:
From the ROBLOX Dev forums:
local buttonPressed = false --Store whether the button is pressed in a local variable Workspace.Button.Touched:Connect(function(hit) if not buttonPressed then -- Is it not pressed? buttonPressed = true -- Mark it as pressed, so that other handlers don't execute print("Button pressed") wait(1) print("Hi :D") -- Do Stuff buttonPressed = false -- Mark it as not pressed, so other handlers can execute again end end)
This exact code may not fulfil your requirement of having the button only being pressable once, however you could simply remove buttonPressed = false
on line 16 or set the wait
time on line 12 to a very high number. Happy scripting! :)
local Part = workspace.Part Part.Touched:Connect(function(hit) if ready == true then ready = false print("Hi i want your toes") wait(1) -- or whatever time amount so it wont keep getting pressed ready = true end end)