Failed because player left game

After about a week of this issue, I’ve managed to find it. For some reason, I get this error, and this stops the game… how can I stop it?

	for i,v in pairs(game:GetService("Players"):GetPlayers()) do
		if v ~= nil then
			v.Team = game:GetService("Teams"):FindFirstChild("Spectator")
			if v ~= nil then
				v:LoadCharacter()
			end
			wait()
		end
	end
1 Like

To prevent this, you could use pcall. Here is your updated code:

for i,v in pairs(game:GetService("Players"):GetPlayers()) do
	if v ~= nil then
		local success, err = pcall(function()
			v.Team = game:GetService("Teams"):FindFirstChild("Spectator")
		end)
		if v ~= nil then
			v:LoadCharacter()
		end
		wait()
	end
end

The first variable returned by the pcall is whether the function errored or not. If it did, the second variable: err will be the error message. Pcall stands for protected call and it’s named that because your script will still run even if it errors. Hope this helps.

2 Likes

Okay, going to test this. When should I ever use pcall? Something that relates to the player?

I use it in my data handling, I know that.

pcall is a custom error handler, so you should be using it in cases where you’d like to handle the result of an error without that error terminating your current running thread. The most common case for use of pcall right now is DataStore. Outside of that, it’s case dependent.

Use it only when you think you’ll need it.

2 Likes