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 make the Touched event fire only once?

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

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

2 comments

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

0

bruh Why make an object inside the player when you can just make a bool variable -_-

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)

2 comments

0

You can use TouchEnded event to debounce, because he said he need the script stop until the player re-touch.

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

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