for J,q in pairs(workspace.Areas:GetChildren())do local function Y()local function J(J)local Y=(J.EnemiesToSpawnHere:GetChildren())[math.random(1,#J.EnemiesToSpawnHere:GetChildren())].Name local d=(J.CFrame.RightVector*J.Size.X)*(math.random(-50,50)/100)local Q=(J.CFrame.UpVector*J.Size.Y)*(math.random(-50,50)/100)local G=(J.CFrame.LookVector*J.Size.Z)*(math.random(-50,50)/100)local P=((J.Position+d)+Q)+G;(require(enemyFunctions)).SpawnEnemy(Y,P,q.Enemies)end local Y={}for J,q in pairs(q.Enemies:GetChildren())do if not Y[q.Name]then Y[q.Name]=1 else Y[q.Name]=Y[q.Name]+1 end end for q,d in pairs(q.SpawnRegions:GetChildren())do local Q=0 for J,q in pairs(d.EnemiesToSpawnHere:GetChildren())do if Y[q.Name]then Q=Q+Y[q.Name]end end for q=1,d.MaximumEnemies.Value-Q,1 do J(d)end end end if q:FindFirstChild("\069\110\101\109\105\101\115")and q:FindFirstChild("\083\112\097\119\110\082\101\103\105\111\110\115")then Y()q.Enemies.ChildRemoved:Connect(Y)end end

for _,area in pairs(workspace.Areas:GetChildren()) do
	local function RefillEnemies()
		local function SpawnEnemy(spawnRegion)
			local enemyToSpawn = spawnRegion.EnemiesToSpawnHere:GetChildren()[math.random(1,#spawnRegion.EnemiesToSpawnHere:GetChildren())].Name
			local xVectorRandom = spawnRegion.CFrame.RightVector * spawnRegion.Size.X * (math.random(-50, 50) / 100)
			local yVectorRandom = spawnRegion.CFrame.UpVector * spawnRegion.Size.Y * (math.random(-50, 50) / 100)
			local zVectorRandom = spawnRegion.CFrame.LookVector * spawnRegion.Size.Z * (math.random(-50, 50) / 100)
			local spawnPosition = spawnRegion.Position + xVectorRandom + yVectorRandom + zVectorRandom
			require(enemyFunctions).SpawnEnemy(enemyToSpawn, spawnPosition, area.Enemies)
		end
		local enemyCounts = {}
		for _,enemy in pairs(area.Enemies:GetChildren()) do
			if not enemyCounts[enemy.Name] then
				enemyCounts[enemy.Name] = 1
			else
				enemyCounts[enemy.Name] = enemyCounts[enemy.Name] + 1
			end
		end
		for _,spawnRegion in pairs(area.SpawnRegions:GetChildren()) do
			local enemiesInRegion = 0
			for _,enemyToSpawn in pairs(spawnRegion.EnemiesToSpawnHere:GetChildren()) do
				if enemyCounts[enemyToSpawn.Name] then
					enemiesInRegion = enemiesInRegion + enemyCounts[enemyToSpawn.Name]
				end
			end
			for i = 1, spawnRegion.MaximumEnemies.Value - enemiesInRegion do
				SpawnEnemy(spawnRegion)
			end
		end
	end
	if area:FindFirstChild("Enemies") and area:FindFirstChild("SpawnRegions") then
		RefillEnemies()
		area.Enemies.ChildRemoved:Connect(RefillEnemies)
	end
end
