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

Why is the last value in my dictionary the only one cloning?

I am trying to make the next button go through the hairs in order without making a function for each hair, and the only one that actually clones is the last one even though it seems like they all work, and there is no error, any help would be great.

All my variables and items are in the correct place too, I just don't want to post all my code because it's like 300 lines.

Code:


local hair = {
	[1] = game:GetService("ReplicatedStorage"):WaitForChild("Hair"):WaitForChild("Beautiful");
	[2] = game:GetService("ReplicatedStorage"):WaitForChild("Hair"):WaitForChild("Long Straight");
	[3] = game:GetService("ReplicatedStorage"):WaitForChild("Hair"):WaitForChild("Long Puffy");
}


nextHair.MouseButton1Click:Connect(function()
	
	curHair = curHair + 1
	if (curHair > maxHair) then
		curHair = minHair
	end
	
	for i,v in pairs(hair) do
		for j,k in pairs(char:GetChildren()) do
			if (k:IsA("Accessory")) then
				k:Destroy()
			end
		end
		if (i == curHair) then
			local clone = v:Clone()
			clone.Parent = char
			print("Hair: " .. clone.Name)
		end
	end
	
end)

1 answer

Your nested For loop needs to be out of the other For loop.

If i == 3 then it won't run the second For loop thus, you always end up with it printing the last hair. Of course, your other hairs are being cloned although they're destroyed right after they're cloned.

I'm simulating a click with a while loop.

local hairs = {
    [1] = "Beautiful";
    [2] = "Long Straight";
    [3] = "Long Puffy";
}

local charHairs = {}

local curHair = 0
local minHair = 1
local maxHair = #hairs

while wait(1) do	
    curHair = curHair + 1
    if (curHair > maxHair) then
        curHair = minHair
    end

	--Put your second For loop here
	

    for i,hair in pairs(hairs) do 
		--if i == 3 then it won't run the second For loop
		--thus, you always end up with it printing the last hair
		for j,k in pairs(charHairs) do
			if k then
				table.remove(charHairs,j)
				print("Removing: " .. k)
			end
	    end
        if (i == curHair) then 
            print("Inserting: " .. hair)
			table.insert(charHairs,hair)
        end
    end

	for _,hair in pairs(charHairs) do
		print("Hair left: ".. hair) --Hair left will always be the last one
	end
end

3 comments

0

Printing it works fine for me too, but it only clones 1 hair, even though in the output it says it's working

0

It's supposed to only clone 1 hair because in your script it's Destroy()ing the others

0

Oh I see, move your second For loop out and above the For loop it's currently in

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