How to only execute code ones depending if player is in region or not

	game:GetService("RunService").Stepped:Connect(function()
		local partsInRegion = workspace:FindPartsInRegion3(region, part, math.huge)
		for i,v in pairs(partsInRegion) do
			if v.Parent:FindFirstChild("Humanoid") then
				print("found" .. " " .. v.Parent:FindFirstChild("Humanoid").Parent.Name)
				entered = true
			else
				entered = false
			end
		end
	end)
	
	game:GetService("RunService").Heartbeat:Wait()
	while true do
		wait(0.01)
		print(entered)
	end

So currently, when I enter my region, it spams the output with true or false depending if I am in the region or not,

I know that I am running a while true do loop to spam it on purpose, but this is just a example to explain the solution I am looking for.

I am looking for a solution where, entered doesn’t get changed in that RunService loop constantly, only whether player is in region or not


This part might be less confusing and better to understand:

With my old code without the while true do loop it spammed the value of entered, I’ll be replacing the print with the function I want it to execute, and in that case the function will be spammed which is something I don’t want.

local entered = false
game:GetService("RunService").Stepped:Connect(function()
	local partsInRegion = workspace:FindPartsInRegion3(region, part, math.huge)
	local found = false
	for i,v in pairs(partsInRegion) do
		if v.Parent:FindFirstChild("Humanoid") then
			found = true
			break
		end
	end
	if found and not entered then
		entered = true
		print'entered'
	elseif not found and entered then
		entered = false
		print'left'
	end
end)

image

1 Like