Better way to remove objects whenever a player dies or leaves game

My goal is to be able to remove unnecessary objects whenever something happens (e.g player dies or leaves game)

I don’t know any efficient method to do this, my only idea is to store items in some module and destroying those parts on request

Example on how I want it to act

Player casts fireball spell
Player dies or leaves > destroy fireball object

Example on why I need this
Player casts fireball spell
Player dies or leaves > fireball object is left behind

I heard of maids but I don’t quite understand it well enough to know if this is what I’m looking for

You could create a folder on PlayerAdded that is exclusively for the Player, so you can easily just delete the folder and its descendants.

2 Likes

Store the player’s assets in a folder, and clear the folder if the Died event or the PlayerLeaving event is called.

1 Like

That’s a better way of putting it haha.

1 Like

Even better solution (in my honest opinion). Use the CollectionService. Any object that belongs to a player or is created by them, tag it with their username. Then, upon the player’s leaving, simply destroy any objects tagged as such.

This prevents you from needing to rely on a folder as your dependency. You should aim to use as little dependencies as possible. A folder is somewhat restricting in terms of objects in the game hierarchy.

local Players = game:GetService("Players")
local CollectionService = game:GetService("CollectionService")

Players.PlayerRemoving:Connect(function (Player)
    for _, item in pairs(CollectionService:GetTagged(Player.Name)) do
        item:Destroy()
    end
end)

-- Example code
CollectionService:AddTag(workspace.Baseplate, somePlayerName)
7 Likes