How to stop for I,v loop from printing multiple times

When I press the button it prints the name 19 times. How can I avoid this.

for _, model in ipairs(game.ReplicatedStorage.CharacterFiles.CharacterStats:GetChildren()) do
	for _, frame in ipairs(Content:GetChildren()) do
		for _, frame2 in ipairs(frame:GetChildren()) do
			for _, button in ipairs(frame2:GetChildren()) do
				if button:IsA("TextButton") then
					button.MouseButton1Down:Connect(function()

							print(button.Name)
						Refresh()
						local Preview = CharacterModel[button.Name].Outfit1:Clone()
						Preview.Parent = ViewPortCharacter
						local Camera = Instance.new("Camera")
						Camera.Parent = ViewPortCharacter
						Camera.CFrame = Preview.Head.CFrame + Preview.Head.CFrame.LookVector * 3.5
						Camera.CFrame = CFrame.new(Camera.CFrame.Position,Preview.Head.Position)
						ViewPortCharacter.CurrentCamera = Camera
						Outfit()
							Event:FireClient(Player,button.Name,CharactersOutfit)
					end)	
				end
			end
		end
	end
end

You can always break the loop. Also that’s a very redundant script.

1 Like

You’re started the loop tree with this line;

for _, model in ipairs(game.ReplicatedStorage.CharacterFiles.CharacterStats:GetChildren()) do

But not used the model variable anywhere. So everything inside that loop is gonna run for every instance inside, which I assume is 19 things.

game.ReplicatedStorage.CharacterFiles.CharacterStats:GetChildren()
1 Like

I can’t say why it’s printing 19 times. But you have 4 nested loops! I’ve been programming for 20 years and never once have I required a loop nested 4 times. There must be a better way!

Yeah it look’s like their just searching 3 layers deep of children looking for anything that is a button.

@itzF_nny if it doesn’t matter how deep you need to go maybe look into replacing GetChildren() with GetDescendants()

for _, button in Content:GetDescendants() do
	if button:IsA("TextButton") then	
		button.MouseButton1Down:Connect(function()
			print(button.Name)
			Refresh()
			local Preview = CharacterModel[button.Name].Outfit1:Clone()
			Preview.Parent = ViewPortCharacter
			local Camera = Instance.new("Camera")
			Camera.Parent = ViewPortCharacter
			Camera.CFrame = Preview.Head.CFrame + Preview.Head.CFrame.LookVector * 3.5
			Camera.CFrame = CFrame.new(Camera.CFrame.Position,Preview.Head.Position)
			ViewPortCharacter.CurrentCamera = Camera
			Outfit()
			Event:FireClient(Player,button.Name,CharactersOutfit)
		end)	
	end
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.