How would I detect the amount of players touching a block

So Im trying to make a script which detects the amount of players touching a specific block. If theirs 10 people touching it then the number value it prints would be ten if theirs 2 people touching it the value would be 2. But if somebody jumps off the block then it’d decrease. Thats sort of what Im aiming for.

x = ""
function onTouched(hit)
	if hit.Parent:findFirstChild("Humanoid") then
		if x ~= hit.Parent.Name then
			script.Parent.Players.Value = script.Parent.Players.Value + 1
			x = hit.Parent.Name
		end
	end
end

script.Parent.Touched:connect(onTouched)

I made this script to change the value by one if somebody’s on it. But Im unsure how to find a way to detect if someones off it. And a flaw with this is two people are on the circle it constantly increases x instead of keeping it at two.

1 Like

You could put players in a table whenever their HumanoidRootPart touched the part, and remove them from the table when their HumanoidRootPart leaves the part (using .TouchEnded).

I could thanks but I still wouldn’t be able to stop the counter from constantly rising.

You could use BasePart:GetTouchingParts() and go from there

Hope this helps!

script.Parent.Players.Value = script.Parent.Players.Value -1

Cache each player that has touched it, and put them into a blacklist from being able to “re-enter”. However, instead of just using the touched event alone, I’d prefer using a combination of BasePart:GetTouchingParts, Touched and Region3.

local tbHmn={}
function onTouched(hit)
	local hmn= hit.Parent:FindFirstChild'Humanoid'
	if not hmn then return end
	if table.find(tbHmn,hmn) then return end
	table.insert(tbHmn,hmn)
end
function onTouchedEnded(hit)
	local hmn= hit.Parent:FindFirstChild'Humanoid'
	if not hmn then return end
	local pos=table.find(tbHmn,hmn)
	if not pos then return end
	table.remove(tbHmn,pos)
end
script.Parent.Touched:connect(onTouched)
script.Parent.TouchedEnded:Connect(onTouchedEnded)
print(#tbHmn)--- here is count (as x)

It will solve your problem. If you do not know the board you should do a little research. # operator returns the length of the table, similar to the variable x

1 Like