Looping through players

I’m using this function to reset all players I don’t know if saying “if player” will result in an error in an error if the player leaves the game. Is there a better solution

	for index, player in pairs(game:GetService("Players"):GetPlayers()) do
		if player.Team.Name == "Playing" then
			local pickedIsland = RandomFunctions.PickARandomItemFromTable(game:GetService("Workspace").Spawns:GetChildren())
			player.Team = game:GetService("Teams").Spectator
			if player then
				local NewValue = Instance.new("IntValue")
				NewValue.Value = tick()
				NewValue.Name = "EndTick"
				NewValue.Parent = PlayerRoundData[player.Name]
				player:LoadCharacter()
			end
		end
	end

Run a protected call to prevent the script from erroring and causing the game loop to break whenever they leave.

1 Like

Yeah but is there a way to check if the player still exists before doing this

local NewValue = Instance.new("IntValue")
NewValue.Value = tick()
NewValue.Name = "EndTick"
NewValue.Parent = PlayerRoundData[player.Name]
player:LoadCharacter()

Don’t just check player, check player.Parent. If it’s nil, the player has already left.

1 Like

So like this???

	for index, player in pairs(game:GetService("Players"):GetPlayers()) do
		if player.Team.Name == "Playing" then
			local pickedIsland = RandomFunctions.PickARandomItemFromTable(game:GetService("Workspace").Spawns:GetChildren())
			player.Team = game:GetService("Teams").Spectator
			if player.Parent then
				local NewValue = Instance.new("IntValue")
				NewValue.Value = tick()
				NewValue.Name = "EndTick"
				NewValue.Parent = PlayerRoundData[player.Name]
				player:LoadCharacter()
			end
		end
	end

This will pretty much always return. I believe this will work as intended but I’m not entirely sure on that

if game.Players:FindFirstChild(player.Name) then

This is what I use. This checks players and if it finds a match it will return.

1 Like

If you are worrying about the player leaving while the loop is running then pcall (protected call) is the way to go

1 Like

PlayerService:GetPlayers() will return an array of every player connected to the game and won’t be nil when accessing the player instance itself.

Also, I suggest switching to ipairs as pairs are mainly used for dictionaries, ipairs are used for arrays.

1 Like

If the player leaves while i’m looping throu won’t player.Name = nil

That’s the point of the if statement. If the player doesn’t exist then the code inside that if statement doesn’t fire. That if statement is making sure Player.Name doesn’t = nil

1 Like

Regardless, your current code is completely fine. If the player doesn’t exist then that code doesn’t run. It will not break your script.

1 Like