I noticed my script that handles the players life cycle was not working 100% of the time so I looked up code on Roblox.
The new code works great. It runs every function every time (as expected).
I only have on question:
In the CharacterAppearanceLoaded, the connection is handled differently than everywhere else.
I do not know why. I also worry that it is a memory leak because it looks like it just keeps reconnecting until the player leaves the experience.
LINK TO ROBLOX: Player | Documentation - Roblox Creator Hub
MY CODE:
--==============
-- PLAYER ADDED
--==============
-- SOURCE: https://create.roblox.com/docs/reference/engine/classes/Player#LoadCharacter
-- SOURCE: https://create.roblox.com/docs/reference/engine/classes/Player#CharacterAdded
-- SOURCE: https://create.roblox.com/docs/reference/engine/classes/Player#CharacterAppearanceLoaded
-- SOURCE: https://create.roblox.com/docs/reference/engine/classes/Player#CharacterRemoving
local Players = game:GetService("Players")
local RESPAWN_DELAY = 5
Players.CharacterAutoLoads = false
local function PlayerAdded(player)
print(player.Name .. "'s player has been added")
--=================
-- CHARACTER ADDED
--=================
local function CharacterAdded(character)
print(character.Name .. "'s character has been added")
local humanoid = character:WaitForChild("Humanoid")
local function CharacterDied()
print(character.Name .. "'s character has died")
task.wait(RESPAWN_DELAY)
player:LoadCharacter()
end
humanoid.Died:Connect(CharacterDied)
end
player.CharacterAdded:Connect(CharacterAdded)
--====================
-- CHARACTER REMOVING
--====================
local function CharacterRemoving(character)
print(character.Name .. "'s character has been removed")
end
player.CharacterRemoving:Connect(CharacterRemoving)
--===================
-- APPEARANCE LOADED
--===================
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
print(character.Name .. "'s character appearance has been loaded")
-- All accessories have loaded at this point
--local numAccessories = #character:GetAccessories()
--print(("Destroying %d accessories for %s"):format(numAccessories, player.Name))
--local humanoid = character:FindFirstChildOfClass("Humanoid")
--humanoid:RemoveAccessories()
end)
-- Make sure we disconnect our connection to the player after they leave
-- to allow the player to get garbage collected
player:LoadCharacter()
player.AncestryChanged:Wait()
connection:Disconnect()
end
for _, player in Players:GetPlayers() do
task.spawn(PlayerAdded, player)
end
Players.PlayerAdded:Connect(PlayerAdded)
--=================
-- PLAYER REMOVING
--=================
-- SOURCE: https://create.roblox.com/docs/en-us/reference/engine/classes/Players#PlayerRemoving
local function PlayerRemoving(player)
print(player.Name .. " has left the experience")
end
Players.PlayerRemoving:Connect(PlayerRemoving)