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

How can I make the Touched event fire only once?

Asked by 4 years ago

I wrote this script to show a problem I am having. When a humanoid touches this part it shows that the part is touched thousands of times. How would I rewrite this script so that when the part is touched by a humanoid, the function will run only once until retouched.

countNumber = 0
script.Parent.Touched:Connect(function(part)
    if part.Parent:FindFirstChild("Humanoid") ~= nil then
        countNumber = countNumber + 1
        print(countNumber)
    end
end)

2 answers

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago
game.Players.PlayerAdded:Connect(function(plr)
    local IfTouched = Instance.new("BoolValue", plr)
    IfTouched.Name = "IfTouched"
end)

script.Parent.Touched:Connect(function(hit)
    if hit and hit.Parent and hit.Parent:WaitForChild("Humanoid") then
        local _plr = game.Players:GetPlayerFromCharacter(hit.Parent)
        if _plr.IfTouched.Value == false then
            IfTouched.Value = true
                countNumber = countNumber + 1
                print(countNumber)
        end
    end
end)

Basically makes a value inside the player so when the player steps on the brick it turns the value to true and then if they touch it again it won't work because it will only work if the value is false

0
thats really nasty code. just make a variable, this code will forever make me cry. you took the time to find a bool inside a player, and create one in a player that will work *once*... duuuuude, a simple boolean could have done the trick T_T greatneil80 2647 — 4y
0
bruh Why make an object inside the player when you can just make a bool variable -_- DizzyGuy70 38 — 4y
Ad
Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

This is actually very simple. You just need to add a "debounce". Here's the code:

countNumber = 0
local Touched = false -- This is a "debounce"
script.Parent.Touched:Connect(function(part)
    if Touched == false then
        if part.Parent:FindFirstChild("Humanoid") ~= nil then
            Touched = true
            countNumber = countNumber + 1
            print(countNumber)
            wait(1) -- Feel free to change the time to the time you want to wait before a player can touch the part again.
            Touched = false
        end
    end
end)
0
You can use TouchEnded event to debounce, because he said he need the script stop until the player re-touch. Block_manvn 395 — 4y
0
It's still somewhat the same isn't it? Except one fires when the player begins touching the part and the other fires after the player touches the part guest_20I8 266 — 4y

Answer this question