Function when a player enters and exit part? (region?)

I’ve written the code below in order to track how many players of each team are touching the part at one time, “numRed” and “numBlue.”

Unfortunately, when a player is inside of the part, it will run both the Touched event and the TouchEnded event tens of times per second, which effectively keeps the count as 0. I’ve seen several similar threads to this, but they each contain code that is significant to a single player rather than the object.

If anyone could give me some tips on this I’d greatly appreciate it!

Part.Touched:Connect(function(hit) --function works properly, however runs 100x/sec
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if player then
		if player.TeamColor == BrickColor.new("Bright red") then
			numRed += 1
		elseif player.TeamColor == BrickColor.new("Bright blue") then
			numBlue += 1
		end
	end
end)

Part.TouchEnded:Connect(function(hit)  --function works properly, however runs 100x/sec
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if player then
		if player.TeamColor == BrickColor.new("Bright red") then
			numRed -= 1
		elseif player.TeamColor == BrickColor.new("Bright blue") then
			numBlue -= 1
		end
	end
end)
1 Like

Add a debounce.

That’s what I wanted to do, and the issue is even the leaving function spams 100x per second, so if I had a debounce in there it would be useless.

local touched = false
local touchedEnded = false

Part.Touched:Connect(function(hit) --function works properly, however runs 100x/sec
	if touched then
		touched = false
		wait(5)
		return
	end
	touched = true
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if player then
		if player.TeamColor == BrickColor.new("Bright red") then
			numRed += 1
		elseif player.TeamColor == BrickColor.new("Bright blue") then
			numBlue += 1
		end
	end
end)

Part.TouchEnded:Connect(function(hit)  --function works properly, however runs 100x/sec
	if touchedEnded then
		touchedEnded = false
		wait(5)
		return
	end
	touchedEnded = true
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if player then
		if player.TeamColor == BrickColor.new("Bright red") then
			numRed -= 1
		elseif player.TeamColor == BrickColor.new("Bright blue") then
			numBlue -= 1
		end
	end
end)

Then just use a double debounce, 1 for each function.

Was just making that edit before you replied.

Use GetPartsinPart instead: https://devforum.roblox.com/t/introducing-overlapparams-new-spatial-query-api

For your use case, you can set OverlapParams such that only player’s characters will be included.