With this post I’d like to briefly cover three most common scenarios and explain them.
1. Server script
In case we are waiting for character to be added on the server, need to wait for it to be added into workspace.
game:GetService("Players").PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
-- further code
end)
end)
Each time player respawns, they are assigned a new character. The old character is destroyed and cleared from memory unless it’s strongly referenced. Player manages the new character that appears in workspace. CharacterAdded fires each time a character model is assigned to certain player instance.
But doesn’t leaving connections like this potentially cause memory leaks? No, not in this case, since all those connections are eventually disconnected and cleared once player leaves the game.
Open this fold to see what not to do and why.
game:GetService("Players").PlayerAdded:Connect(function(player)
-- Find existing character or wait for it to be added.
local character = player.Character or player.CharacterAdded:Wait()
-- further code
end)
--[[
Why won't this work well? It will first time player joins, but
nothing will happen after player respawns.
"character" variable only stores the last character, even when it
is removed. Any changes done to it won't be visible on new character
nor its descendants.
]]
Others have already explained this.
2. Local script - StarterCharacterScripts
All scripts that are located in StarterCharacterScripts are inserted into player’s character model. That means each time new character spawns, all these scripts will activate again. Not only is .CharacterAdded event unnecessary here, but it burdens memory for no reason.
DO NOT CONNECT .CharacterAdded in LOCAL SCRIPTS! (Sorry, had to stress it out.
)
local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
Voila! Simple, right? You should use StarterCharacterScripts for any scripts that should be part of newly parented character.
3. Local script - StarterPlayerScripts
What is the catch here? Local scripts located here are not inserted into any characters, but rather remain in player instance. They are not freshly inserted after player respawns, and stay on spot until player leaves os player instance changes. The process is similar to server script scenario, although you shouldn’t use StarterPlayerScripts to do changes on active character. If you are managing camera, for example, StarterPlayerScripts are a good choice.