Problem when a player leaves during an iteration

Hello!

I have a round system in my game, but I have an issue. If a player leaves directly after winning, the script errors.

“Cannot set player’s team because they left the game”
I tracked this down to a loop that loops through every player.

local players = game:GetService("Players")
local teams = game:GetService("Teams")

for _, player in pairs(players:GetPlayers()) do
    if not players:FindFirstChild(player.Name) then continue end
    if not player.Character then continue end
    player.Team = teams.Dead --this line still errors
end

Despite the efforts above, it still errors. Any help is appreciated.

1 Like

Really weird issue, could you try this and see if that works?

local players = game:GetService("Players")
local teams = game:GetService("Teams")

for _, player in pairs(players:GetPlayers()) do
	if player:IsA("Player") then 
		player.Team = teams.Dead
	else
		continue
	end
end

it might be a timing issue and this could fix that

2 Likes

It would seem that since this error requires a very specific timing, then it’s not really that much of an issue. However, if you really do want to completely stop it from breaking things later in the loop, even at such minimal chances, a protected call should suffice.

local success, err = pcall(function()
     -- code goes here
end)

if success then
     print("function success")
else
     print("function error:", err)
end
1 Like

I already tried a pcall() and it didn’t work - the loop still stopped, but no error thrown because it was caught by the pcall()

I might give it another go though

Thanks! I now have 4 lines which check if the player is still in the game (a bit over the top and some are duplicates), each one of them works now…

if not players:FindFirstChild(player.Name) then continue end
if not player.Character then continue end
if not player:IsA("Player") then continue end
if not workspace:FindFirstChild(player.Name) then continue end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.