Detect if player enters and leaves part

How would one make a script that optimally checks if a player enters a part (maybe by touch events) and if they leave the part (or step off if it’s collidable)? This is for an automatic door system which simulates motion sensing.

I don’t really want to use modules. I prefer taking inspiration and making my own script from scratch.

Introducing OverlapParams - New Spatial Query API - Updates / Announcements - Developer Forum | Roblox

2 Likes

You want to use a table to keep track for players who are touching it. If they touched it for the first time, we add them to the table. If they stopped touching it we can remove them

local part = -- Part here
local TouchedPlayers = {}
part.Touched:Connect(function()
   if hit.Parent:FindFirstChild('Humanoid') and not table.find(TouchedPlayers,hit.Parent)
      print('Player touched part')
   end
end)
part.TouchEnded:Connect(function()
   if hit.Parent:FindFirstChild('Humanoid') and table.find(TouchedPlayers,hit.Parent)
      print('Player stopped touching part')
   end
end)
1 Like

My guy. Thanks a bunch.

local characters = {}
		
sensorPart.Touched:Connect(function(hitPart)
	if hitPart.Parent:FindFirstChild('Humanoid') and not table.find(characters, hitPart.Parent) then
		table.insert(characters, hitPart.Parent)
		print("began")
	end
end)

sensorPart.TouchEnded:Connect(function(hitPart)
	if hitPart.Parent:FindFirstChild('Humanoid') and table.find(characters, hitPart.Parent) then
		print("ended")
		table.remove(characters, table.find(characters, hitPart.Parent))
	end
end)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.