Is it necessary to destroy all instances that don't have parent that I won't be using anymore?

Hello. I have some questions about instance.

If I create an instance that has no parent and store it in a variable and overwrite that variable, should I destroy the instance first?

Example code:

local CharacterLoaded = false

-- Function 1: Destroying instance
local function LoadCharacter(player, parent)
	player.CharacterAppearanceLoaded:Connect(function()
		CharacterLoaded = true
	end)

	local character1 = Players:CreateHumanoidModelFromUserId(player.UserId)
	local character2 = Players:CreateHumanoidModelFromDescription(character1.Humanoid.HumanoidDescription, Enum.HumanoidRigType.R6)
    character1:Destroy()
	character2.Parent = parent or workspace
	character2:MoveTo(workspace.SpawnLocation.Position + Vector3.new(0,5,0))
	player.Character = character2

	repeat wait() until CharacterLoaded == true
end

-- Function 2: Not destroying instance
local function LoadCharacter(player, parent)
	player.CharacterAppearanceLoaded:Connect(function()
		CharacterLoaded = true
	end)

	local character = Players:CreateHumanoidModelFromUserId(player.UserId)
	character = Players:CreateHumanoidModelFromDescription(character.Humanoid.HumanoidDescription, Enum.HumanoidRigType.R6)
	character.Parent = parent or workspace
	character:MoveTo(workspace.SpawnLocation.Position + Vector3.new(0,5,0))
	player.Character = character

	repeat wait() until CharacterLoaded == true
end

local Characters = Instance.new('Folder')
Characters.Name = 'Characters'
Characters.Parent = workspace

local test_player = game:GetService('Players')['Player1']
LoadCharacter(test_player, Characters)

which of these functions is correct?

Or if I create an instance that doesn’t have a parent and store it in a variable and I don’t use that variable anymore, should I destroy it?

Example code:

local part = Instance.new('Part')
part.Name = 'Block'
print(part.Name)

-- Destroying part
part:Destroy()
1 Like

Yes, regardless of where an instance is parented (including nil), it will never be garbage collected unless it is destroyed which is recipe for disaster.

Having something un-referenced or not traceable, but not garbage collected is called a memory leak. The aforementioned instance will always take up some amount memory. In fact, any instance in your game will. Sure it takes up a negligible amount at first but as time goes on, the amount of memory that’s taken up will increase and will never be freed until the player leaves the game if you don’t call :Destroy. Therefore it’s always a good idea to destroy instances you don’t need anymore.

PS. you can halt the thread until the character appearance loads by doing player.CharacterAppearanceLoaded:Wait() instead of making a variable and repeat waiting.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.