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
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.
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.