Code sample Remove Accessories After Loading needs a small update

Page URLs:

Remove Accessories After Loading sample throws an error in line 6 - GetAccessories() is a method of humanoid, not character model.

Lines 14 and 15 are not really necessary. New Player and Character Destroy Behavior is about to become enabled by default and is announced to become permanent behaviour around June this year. Even when disabled, disconnecting alone is not enough for the Player object to be released from memory as the comments say. The majority of other code samples don’t disconnect events like CharacterAdded and CharacterRemoving either. (With workspace.PlayerCharacterDestroyBehavior disabled, manually destroying player and character instances is much more effective as well.)

New:

local Players = game:GetService("Players")

local function onPlayerAdded(player)
    player.CharacterAppearanceLoaded:Connect(function(character)
        -- All accessories have loaded at this point
        local humanoid = character.Humanoid
        local numAccessories = #humanoid:GetAccessories()
        print(`Destroying {numAccessories} accessories for {player.Name}`)
        humanoid:RemoveAccessories()
    end)
end

for _, player in Players:GetPlayers() do
    task.spawn(onPlayerAdded, player)
end
Players.PlayerAdded:Connect(onPlayerAdded)

Thanks for reporting! Great catch on the error. Looks like we already have a newer version of this code sample that fixes this but it isn’t published yet. I’ll make sure that gets through soon and update here when it’s live.

As for the player destroy behavior, we have an open ticket to audit the rest of the code samples for this potential memory leak. But as you say, it may soon be a moot point thanks to the new PlayerCharacterDestroyBehavior that will destroy players and potentially characters by default, so we’ll leave them be unless it seems like plans change for the release of the new destroy behavior.

For now, we can leave the disconnection in this sample, but we can remove it once the new destroy behavior is default.

Late edit: :LoadCharacter() is fixed to now be on Humanoid.

1 Like