Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I make a Touched event happen only once?

Asked by 3 years ago

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!

3 answers

Log in to vote
1
Answered by
QWJKZXF 88
3 years ago

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)

0
what wizz_zz 3 — 3y
Ad
Log in to vote
0
Answered by
yodafu 20
3 years ago
Edited 3 years ago

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! :)

Log in to vote
0
Answered by
A_Mp5 222 Moderation Voter
3 years ago
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)

Answer this question