Folder created way too much times

Hello Everybody

So I am working on a pet Inventory system. I am making the unequip button, but a current event in the script runs way too much. That is a folder being replicated too many times. Look at the photos below
Screenshot 2022-07-16 125427
If you spam the Unequip button way too many times that is what happens. This creates lag and throws off other scripts.
Local Script

local Unequip = script.Parent
local template = script.Parent.Parent.Parent.Parent.Parent
local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local AmountEquippedValue = game.Players.LocalPlayer.PlayerGui:WaitForChild("Inventory").LowerInvFrame.AmountEquipped.AmountEquippedValue-- Amount of total pets Equipped 
local UnequipPet = game.ReplicatedStorage:WaitForChild("UnequipRE")-- Remote Event for Unequipping the pet


local Inventory = game.Players.LocalPlayer.PlayerGui:WaitForChild("Inventory")
local AmountEquipped = Inventory.LowerInvFrame.AmountEquipped
local amountEquippedValue =  AmountEquipped.AmountEquippedValue 
-- defining the UI




Unequip.Activated:Connect(function()
	print(amountEquippedValue)
	local EquippedValue = template:WaitForChild("EquippedValue")
	EquippedValue.Value = "Unequipped" -- value in template to store info

	template.check.ImageColor3 = Color3.fromRGB(251, 254, 255)-- check mark indicating if a pet is Equipped or not, green if Equipped
	
	for _, child in pairs(template:GetChildren()) do -- checking all children of template
		if child:IsA("StringValue") and child.Name == "PetName" then 
			if child.Value == "Cat" then -- looking for the pet 
				
				
				local CatFolder = Instance.new("Folder")
				CatFolder.Name = "Cat"
				CatFolder.Parent = template 
				
				
				UnequipPet:FireServer(child,char,amountEquippedValue) -- fire the remote event

				end
			end
			

end
		end)


Screenshot 2022-07-16 125507
This right here is the block of code that replicates the folder into the template.
Is there a way for this block of code to run only if the template has no other folder?

1 Like

Have you considered using a debounce?

Yes, the thing is debounce only temporarily fixes it.

yes you would check if template has childofclass Folder

ex:

if template:FindFirstChildOfClass("Folder") then
return
--existing folder found do not add another folder
end
1 Like