The code show on the page CharacterAutoLoads should not be used as an example.
It is very poorly made.
- Uses an infinate loop
while true do -- code end
- Promotes the use of loops over events needlessly increasing the complexity
- Uses Remove and not Destroy
- Uses
game.Players:GetChildren()
and notgame.Players:GetPlayers()
The current code is:-
-- Set CharacterAutoLoads to false
game.Players.CharacterAutoLoads = false
-- Remove player's character from workspace on death
game.Players.PlayerAdded:Connect(function(player)
while true do
local char = player.CharacterAdded:wait()
char.Humanoid.Died:Connect(function()
char:Remove()
end)
end
end)
-- Respawn all dead players once every 10 seconds
while true do
local players = game.Players:GetChildren()
-- Check if each player is dead by checking if they have no character, if dead load that player's character
for i, player in pairs (players) do
if (not game.Workspace:FindFirstChild(player.Name)) then
player:LoadCharacter()
end
end
-- Wait 10 seconds until next respawn check
wait(10)
end
Example of updated code:-
-- reduce duplicate code with variables
local plrServ = game:GetService("Players")
plrServ.CharacterAutoLoads = false -- disable auto spawn
plrServ.PlayerAdded:Connect(function(plr)
plr.CharacterAdded:Connect(function(charModel)
charModel:WaitForChild("Humanoid").Died:Connect(function()
charModel:Destroy() -- delete players model
end)
end)
end)
while true do
print("Spawning players")
local i = 0
for _, plr in pairs(plrServ:GetPlayers()) do
if not workspace:FindFirstChild(plr.Name) then
i = i + 1
plr:LoadCharacter()
end
end
print(i, "Players spawned in")
wait(10)
end