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

Generic for i,v loop with MouseButton1Click isn't working?

for i,v in pairs(script.Parent:GetChildren()) do


script.Parent.MouseButton1Click:connect(function(player)
	game.Workspace.Display.LoadedBy.Main.Body.Text = game.Players.LocalPlayer.Name
	game.Players.LocalPlayer.PlayerGui.Training.Trainer.Change.SelectedMap.Text = "Selected map: ".. script.Parent.Name
	
end)
end

They're textbuttons, and whenever I click one of the Children, the following SHOULD happen, but it doesn't seem to work

1 answer

✓ Accepted answer

Problem

You're not using the value that your iterator (pairs) returns, your v variable. This is the variable that represents the value associated with your i variable (your index variable). All you're doing traversing through a table of objects, assigning a MouseButton1Click event to the same object over and over again (where you have script.Parent.MouseButton1Click).

Solution

What you want to do, is make it so each of the objects you're iterating through gets that MouseButton1Click event. This is pretty easy to accomplish since the value of each individual object is given to you in your v variable as mentioned above.

Now before we just replace script.Parent with v, let's also make sure the object we're working with is a TextButton, so your code doesn't error if there's a different object in your table. For this we'll just add an if statement before creating the event. Here's an example:

-- Quick reference to the local player
local Player = game:GetService("Players").LocalPlayer
local PlayerGui = player:WaitForChild("PlayerGui")

for i,v in pairs(script.Parent:GetChildren()) do
	if v:IsA("TextButton") then -- Makeing sure it's a TextButton

		-- Fixes:
		-- Removed the 'player' parameter, as it's redundant in this event
		-- Replaced 'script.Parent' with 'v', your mutable value
		v.MouseButton1Click:connect(function()
			game.Workspace.Display.LoadedBy.Main.Body.Text = Player.Name
			PlayerGui.Training.Trainer.Change.SelectedMap.Text = "Selected map: ".. Player.Name
		end)

	end -- End if statement
end -- End for loop

Hope that helped, let me know if you have any questions.

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