Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to make it so a person doesn't spam the onTouched event ?(PLEASE LOOK)

How do I make this so a person can not spam the onTouched event?

`function onTouched() Instance.new("Hint", game.Workspace) wait() game.Workspace.Message.Text="Worked" wait(5) game.Workspace.Message:Remove()

end

script.Parent.Touched:connect(onTouched)`

1 comment

0

Please format your code in Lua code block.

3 answers

Perhaps make sure that the object touching the part is an actual player, else any brick could touch it. ;)

function onTouched(Hit)
	local Player = Hit.Parent and Hit.Parent:FindFirstChild("Humanoid") and Hit.Parent.Humanoid.Health > 0 and game.Players:GetPlayerFromCharacter(Hit.Parent)
	if Player then
		local MSG = Instance.new("Hint", game.Workspace) -- Define this new instance with a variable. You'll have more control over the object you're making.
		wait()
		MSG.Text="Worked"
		wait(5)
		MSG:Destroy() -- This locks the message in "nil." ":Remove()" is deprecated.
	end
end

script.Parent.Touched:connect(onTouched)

Debounce is a very useful concept to learn. It means that you can only process one chunk of executions at a time. It's like regenerating a car (if you're an old ROBLOX player like me, you remember this ;)), the purple regenerating button turns black for a certain amount of time. Then becomes back to purple, allowing you to regenerate the car again.

The most common way of implementing this is to manipulate a static variable and wrap an "if" statement around your chunk of code.

Debounce = false

function onTouched(Hit)
	local Player = Hit.Parent and Hit.Parent:FindFirstChild("Humanoid") and Hit.Parent.Humanoid.Health > 0 and game.Players:GetPlayerFromCharacter(Hit.Parent)
	if Player then
		if not Debounce then
			Debounce = true
			local MSG = Instance.new("Hint", game.Workspace)
			wait()
			MSG.Text="Worked"
			wait(5)
			MSG:Destroy()
			Debounce = false
		end
	end
end

script.Parent.Touched:connect(onTouched)

2 comments

0

No point in checking hit.Parent

0

Lmao, I'm very paranoid that the parent of hit could be nil.

Debounce

debounce = false

function onTouched() Instance.new("Hint", game.Workspace) 
if not debounce then debounce = true
wait() 
game.Workspace.Message.Text="Worked" 
wait(5) 
game.Workspace.Message:Remove()
debounce = false
end

script.Parent.Touched:connect(onTouched)`

2 comments

0

Gives a error on the "script.Parent.Touched:connect(onTouched)" part

0

That's because there's a stray "`" at the end of that line. It should work without that, but, Zeloi, please elaborate more on your explanations.

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