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

How to make a part add points whilst being touched and only whilst being touched?

What I have so far works, but it's not without it's problems. So what I want is for it to add 1 every 1 second and only do this whilst the player is touching the part. What I think is happening is that it somehow keeps triggering the touch event without triggering the touchended.

part = script.Parent
HMain = game.Workspace.HMain.Value
stopped = false

part.Touched:connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		stopped = false -- Set to false so we know we're touching it.
		while stopped == false do -- If we're touching it then.
			stopped	= true -- Set to true so we can't trigger this again until it's done.
			HMain = HMain + 1
			print(HMain)
			wait(1)
			stopped = false -- Set to false so we can trigger the while loop again.
		end
	end
end)

part.TouchEnded:connect(function()
	print("Stopped")
	stopped = true	-- So we can't trigger it anymore.
end)

1 answer

✓ Accepted answer

I recommend a while loop.

local part = script.Parent
local HMain  = workspace.HMain
local touching = false

part.Touched:connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		touching = true
	end
end)

part.TouchEnded:connect(function()
	touching = false
end)

while true do
	if touching then
		HMain = HMain + 1
		wait(1)
	end
	wait()
end

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