Scripts inside a tool continue to run even after the tool is destroyed?

I was fooling around earlier today with tools and I realized that even if you destroy a tool the code after the :Destroy() command will still run and I was honestly just curious as to how this is possible if the script no longer exists? I forcefully unequip the tool and then when it gets placed inside the backpack I destroy the tool and yet the code below the :Destroy() line continues to run even know the script no longer exists.

This is an example of some code I have that runs after the module script gets requested. The script that requests the module script is also a part of the tool. The while loop continues to print even after the script no longer exists.

function Module.Fire()
	local Character = Tool:FindFirstAncestorWhichIsA("Model")
	local Player = Players:GetPlayerFromCharacter(Character)
	
	ClientInputEvent.OnServerEvent:Connect(function()
		local HuntImmunity = Instance.new("BoolValue")
		HuntImmunity.Name = "HuntImmunity"
		HuntImmunity.Parent = Character
		
		for Index, Object in ipairs(Data[Player.UserId].TemporaryData:GetChildren()) do
			if string.find(Object.Name, "Tool") ~= nil and Object.Value == Tool.Name then
				Object.Value = ""
			end
		end
		
		Character.Humanoid:UnequipTools()

		Player.Backpack:FindFirstChildWhichIsA("Tool"):Destroy()
		
		while true do
			print(1)
		end
	end)
end

If anyone could help me to understand how this works I would be really thankful. Thanks and have a good one!

What Roblox does, is creates Instances that all have an ‘ultimate’ parent called the game. When you :Destroy() something or make something ‘nil’, the object’s ‘ultimate’ parent is now made a child of a ‘nil’ array, a table which the game ignores. When you destroy something you simply switch its parent to nil. You can easily test this with a script:

local Part = Instance.new('Part', workspace)
Part:Destroy()
print(Part.Parent) -- Will print 'Nil' as it is now a part of the 'nil' array.

With this idea in mind, you can also bring an object back from the nil array by simply setting its parent back to an existing class. If you :Destroy() an object and set the reference variable to nil, then you won’t be able to access that original part.
Therefore whatever script inside the object that is destroyed will still run if it has loops that did not finish, but it will run without a source.

2 Likes

@ADRENALXNE seems to have covered why it continues running, but if you want to make sure it doesn’t run, just set the Disabled variable to true.

1 Like