Issue with Values from Vector3 Table Coming Up as "Nil"

I have this script that generates a list of potential spawn points, runs a loop through all the players and assigns them a random point, and teleport them to that point.

I’d say that 90% of the time, this works fairly well, but the 10% of the time, it fails, with the below error code:

Here is the below code:

local function individualSpawn(i:Vector3, player:Player)
	local char = player.Character or player.CharacterAdded:Wait()
	player:SetAttribute("spawnPos",i)
	char:MoveTo(i)
end

local function spawnPlayers(controller:Player)
	local spawns = initializeSpawnPoints()
	task.wait(1)
	for i, player in pairs(Players:GetChildren()) do
		local random = math.random(1,#spawns)
		local choice = spawns[random]
		table.remove(spawns,random)
		print(tostring("size: "..tostring(#spawns)))
		task.wait()
		task.spawn(function()
			print(tostring(player).." will spawn at option #"..random..", "..tostring(spawns[random]))
			if controller and player == controller then return end
			individualSpawn(spawns[random],player)
		end)
	end
end

It seems like, somehow, the for loop moves onto the next player before the “spawns” table updates. How do I fix this?

1 Like

You’re feeding spawns[random] into individualSpawn when that exact index was just removed from the array:

table.remove(spawns,random)

Pass choice as it holds the value that was removed. On another note, you can simplify your code to:

local choice = table.remove(spawns, random)
1 Like

Oops. How embarrassing. This could’ve been solved with a simple proof writing. Thanks!