CharacterAutoLoads code sample needs to change

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 not game.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
9 Likes

To further improve this, I think it might a good idea to change the if condition. Imagine if somebody named “Terrain” joins the game.

if plr.Character == nil or not plr.Character:IsDescendantOf(workspace) then
    i = i + 1
    plr:LoadCharacter()
end

I tested something like that but plr.Character is not set to nil after the player is removed. Setting plr.Character = nil on died causes a ton of warning to be present on the client.

I see. The :IsDescedantOf(workspace) should still be effective (and more reliable) in detecting when its parent is set to nil. When doing it this way, you still need to check for the character being nil, so that the script doesn’t error with attempt to index field "Character" (a nil value), just to be safe.

This would avoid all function calls but both of these other methods would increase the complexity when explaining it to users.

if not plr.Character or plr.Character.Parent == nil then