Stopping Timer when player steps out of region3

Hello,

I have had a problem using region3 for a timer for a couple hours. I coded a timer that starts when the player touches the region3. Now, I want to make it to when the player steps outside the region3, the timer would stop. I searched on the dev forum for a while and found a way using tables, but I just don’t know how to implement that into my code. So, How would I make(maybe in a way other than tables) it so the timer stops when the player is out of the region3?

Script:

local part = script.Parent
local players = {}
local region = Region3.new(part.Position - part.Size/2, part.Position + part.Size/2)
local canloop = true

while wait() do
	local partsInRegion = workspace:FindPartsInRegion3(region, part, math.huge)
	for i, part in pairs(partsInRegion) do
		if part.Parent:FindFirstChild("Humanoid") ~= nil then
			local player = game:GetService("Players"):GetPlayerFromCharacter(part.Parent)
			wait(1)
			print("player inside")
			player.leaderstats["Time Alive"].Value = player.leaderstats["Time Alive"].Value + 1
		end
	end
end

Thank you,

Ultan

local part = script.Parent
local players = {}
local region = Region3.new(part.Position - part.Size/2, part.Position + part.Size/2)
local canloop = true

while wait() do
	local partsInRegion = workspace:FindPartsInRegion3(region, part, math.huge)
	for i, part in pairs(partsInRegion) do
		if part.Parent:FindFirstChild("Humanoid") ~= nil then
			local player = game:GetService("Players"):GetPlayerFromCharacter(part.Parent)
			if player then
				print("player inside")
				player.leaderstats["Time Alive"].Value = player.leaderstats["Time Alive"].Value + 1
			elseif not table.find(partsInRegion,player) then
				-- code			
			end
		end
	end
end
1 Like

This won’t work, you’re attempting to find the player itself in the table of parts which were located in the region. The player isn’t a part. If it did work, you’d need a wait otherwise the score would go incredibly high very quickly.

1 Like
local part = script.Parent
local players = game:GetService("Players")
local region = Region3.new(part.Position - part.Size/2, part.Position + part.Size/2)

while task.wait(1) do
	local playerList = players:GetPlayers()
	local partsInRegion = workspace:FindPartsInRegion3(region, part, math.huge)
	for i, part in pairs(partsInRegion) do
		if part.Parent:FindFirstChild("Humanoid") and part.Name == "HumanoidRootPart" then
			local player = players:GetPlayerFromCharacter(part.Parent)
			if table.find(playerList, player) then
				player:WaitForChild("leaderstats"):WaitForChild("Time Alive").Value += 1
			else
				--do something if player not in region
			end
		end
	end
end

Demonstration:
https://gyazo.com/7494e4b081713fd8f7264c6836f45876

1 Like

Oh yeah a bit of an oopsie lol

1 Like