While loop randomly breaks

Hello there.
I am making this game which spawns enemies depending on your current biome.
I have region3 to check if a player is inside of a biome.
However, while testing, I noticed that my while true loop that keeps checking the player’s location stops at a random interval. Does while loops do that?
If this is an error, please point it out.
I copied the loop here.
while wait(4) do
print(“Check”)
biomeBlocks = game.Workspace.RegionParts:GetChildren()
local plrs = game.Players:GetChildren()
for plr = 1,#plrs,1 do
wait(0.2)
for i,v in pairs(biomeBlocks) do
wait(0.2)
local region = area[i]
local playersInRegion = game.Workspace:FindPartsInRegion3WithWhiteList(region,{plrs[plr].Character.HumanoidRootPart})
if playersInRegion[1] then
if playersInRegion[1].Parent == plrs[plr].Character then
plrs[plr].Stats.currentBiome.Value = v.Name
end
end
end
end
end

Sorry that the code doesn’t look optimized.
Thanks to those who respond.
*RegionParts is the parts in the workspace that marks the biomes.

1 Like
while wait(4) do
	print("Check")
	biomeBlocks = game.Workspace.RegionParts:GetChildren()
	local plrs = game.Players:GetChildren()
	for plr = 1,#plrs,1 do
		wait(0.2)
		for i,v in pairs(biomeBlocks) do
		wait(0.2)
		local region = area[i]
		local playersInRegion = game.Workspace:FindPartsInRegion3WithWhiteList(region,{plrs[plr].Character.HumanoidRootPart})
			if playersInRegion[1] then
				if playersInRegion[1].Parent == plrs[plr].Character then
					plrs[plr].Stats.currentBiome.Value = v.Name
				end
			end
		end
	end
end

Better format!

Try this:

while wait() do
	print("Check")
	biomeBlocks = game.Workspace.RegionParts:GetChildren()
	local plrs = game.Players:GetChildren()
	for plr = 1,#plrs,1 do
		for i,v in pairs(biomeBlocks) do
		local region = area[i]
		local playersInRegion = game.Workspace:FindPartsInRegion3WithWhiteList(region,{plrs[plr].Character.HumanoidRootPart})
			if playersInRegion[1] then
				if playersInRegion[1].Parent == plrs[plr].Character then
					plrs[plr].Stats.currentBiome.Value = v.Name
				end
			end
		end
	end
end

This might work!

Thanks for the response!
I will try it out now.
Also could you tell me how to got the code to format like that?

Yeah, so when if you select you code and do Ctrl+shift+C it should format it or you can do it manually by pressing:
image

Thanks.
Could you explain why changing the wait from wait(4) to wait() would help?

Well you don’t really need that many wait, since you already have a wait in the while wait() do. Well as for your problem everything should work fine, the only reason I removed the wait is because it’s not needed.

1 Like