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