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

How can you tell when something STOPS touching another object?

For example, if I wanted to tell how long that a particular player was inside an object, how would I tell when they went out of contact with that object?

All support is appreciated, thanks!

2 answers

The TouchEnded Event does that.

So to do what you want;

db = false

script.Parent.Touched:connect(function(hit)
	if db == false then db = true end
	if hit.Parent:FindFirstChild("Humanoid") ~= nil then
		before = tick()
		script.Parent.TouchEnded:wait()
		after = tick()
		tm = math.floor(after - before)
		print("Player was touching part for "..tm.." seconds!")
	end
	db = false
end)

-Goulstem

1 comment

0

@Ekkoh, the debounce prevents that.

Adding on to Goulstem's response, that would not work as expected if another part touches and stops touching the part, it will act as if the original part has stopped touching it. This is what I would do.

db = false

script.Parent.Touched:connect(function(hit)
	if db == false then db = true end
	if hit.Parent:FindFirstChild("Humanoid") ~= nil then
		before = tick()
		local c
		c = script.Parent.TouchEnded:connect(function(hit2)
			if hit2 == hit then
				tm = math.floor(tick() - before)
				print("Player was touching part for "..tm.." seconds!")
				c:disconnect()
			end
		end)
	end
	db = false
end)

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