Destroy is not working

Script:

for _, template in pairs(script.Parent.PlayersTemplate:GetChildren()) do
	if template:IsA("Frame") then
		template:Destroy()
	end
end

I am trying to destroy some GUI objects but it doesn’t work

1 Like

Is the thing you are trying to destroy definitely of the correct class in correlation to your check on line 2?

If it’s not a frame it will not be destroyed.

Perhaps print something before the check to see if it’s even iterating through the result of :GetChildren() because if not, it may suggest you’re trying to destroy something before it has been loaded in / been parented to the “PlayersTemplate” object.

I noticed that print and destroy works, but then they reappear.

Are you sure these frames are not ScrollingFrames?
If they are you can just do

if template:IsA("Frame") or template:IsA("ScrollingFrame") then
-- stuff! :O
end

Yes, I’m sure they are all frames.

Screenshot of the explorer, where the frame is and where the script is

Is there any other code which adds the frames?

Here is the screenshot of the explorer:
pic

I suppose the code that adds the frames are in a loop?

Yes, the code removes all frames and then adds new ones but the old ones are not removed.

Yes, the code is in a loop:

local player = game.Players.LocalPlayer

game.ReplicatedStorage.UpdateLeaderboard_lb.OnClientEvent:Connect(function(leaderboardInfo)
	if leaderboardInfo then
		for _, template in pairs(script.Parent.PlayersTemplate:GetChildren()) do
			if template:IsA("Frame") then
				template:Destroy()
			end
		end
		script.Parent.Parent.TopDonators.Text = string.format("TOP %d DONATORS", math.clamp(leaderboardInfo.TopDonatorsAmount, 0, 100))
		for _, user in ipairs(leaderboardInfo.TopDonators) do
			local newTemplate = script.Parent.Template:Clone()
			newTemplate.Name = "PlayerTemplate"
			newTemplate.Username.TextLabel.Text = user.Username
			newTemplate.Amount.TextLabel.Text = user.AmountDonated
			newTemplate.Visible = true
			newTemplate.Parent = script.Parent.PlayersTemplate
		end
		script.Parent.Parent.ScrollingFrame.CanvasSize = UDim2.new(0, script.Parent.PlayersTemplate.UIListLayout.AbsoluteContentSize.X, 0, script.Parent.PlayersTemplate.UIListLayout.AbsoluteContentSize.Y)
	end
end)

So it destroys the frames, but then the old frames reappear?

I found the problem now. The problem was that the passed table is inserting new arrays every 30 seconds and it was never cleared.

1 Like