Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Help with this script duplicating more than once?

I am scripting a building kit and when I press the 'Refresh' button, it supposse to remove all parts in it that have a name of 'Part' and 'Thruss'. Then it suppose to make new parts in it but it is duplicating the parts more than once ;(

--//Services
local RS = game:GetService('ReplicatedStorage')

--//Variables
local Model = script.Parent.Parent
local CD = Model.Refresh.ClickDetector
local Clicked = false

--//Main
CD.MouseClick:connect(function()
	if Clicked == false then
		Clicked = true
		for i,v in pairs(Model:GetChildren()) do
			if v.Name == 'Part' or v.Name == 'Truss' then
				v:Destroy()
				print'1'
				local CloneModel = RS:WaitForChild('BuildingKit') --Make sure the model is in ReplicatedStorage
				for i,x in pairs(CloneModel:GetChildren()) do
					if x.Name == 'Part' or v.Name == 'Truss' then
						x:Clone().Parent = Model
						print'2'
					end
				end
			end
		end
		wait(5)
		Clicked = false
	end
end)

2 comments

0

Btw, this crashes my studio, guessing due to many parts being created

1

line 19, you have x.Name == 'Part' , v.Name == 'Truss" is the x and v on purpose? 

1 answer

✓ Accepted answer

The loop that you're using to duplicate the parts is inside of the loop that you're using to delete parts. All you have to do is put it after that loop:

--//Services
local RS = game:GetService('ReplicatedStorage')

--//Variables
local Model = script.Parent.Parent
local CD = Model.Refresh.ClickDetector
local Clicked = false
local CloneModel = RS:WaitForChild('BuildingKit') --// No need to get the model again every time; just get it once.

--//Main
CD.MouseClick:connect(function()
    if Clicked == false then
        Clicked = true
        for i,v in pairs(Model:GetChildren()) do
            if v.Name == 'Part' or v.Name == 'Truss' then
                v:Destroy()
                print'1'
            end
        end
        for i,x in pairs(CloneModel:GetChildren()) do
            if x.Name == 'Part' or x.Name == 'Truss' then
            	x:Clone().Parent = Model
                print'2'
            end
        end
        wait(5)
        Clicked = false
    end
end)

Hope this helped.

EDIT: I had already fixed it, but I forgot to note that you were also using v when you should have used x on line 19. Thanks, RobloxianDestory, for pointing that out.

1 comment

1

you beat me to it. I was testing it when you answered it

This discussion is preserved as it was. New answers, comments, and votes are closed.