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

For i,v in pairs with mousebutton1down function?

I have a buying system. A player buys a cart, for every cart they purchase, then a ImageButton is created in a ScrollingFrame with a UIGridLayout. I'm assuming my problem is that the pairs function is grabbing the ImageButtons when the script initially runs. There is no image buttons in the scrolling frame until a player buys a cart in-game. I'm not sure a way around that. Here's my script,

game.Players.LocalPlayer:WaitForChild("PlayerGui")
game.ReplicatedStorage.RemoteEvents.updatePlayerCarts:FireServer()
mcstatus = false
mcdb = false
script.Parent.myCartsButton.MouseButton1Down:connect(function()
	if mcstatus == false and mcdb == false then
		mcdb = true
		script.Parent.myCarts:TweenPosition(UDim2.new(.1,0,.2,0))
		script.Parent.myCartslabel:TweenPosition(UDim2.new(.1,0,.135,0))
		wait(1.2)
		mcstatus = true
		mcdb = false
	elseif mcstatus == true and mcdb == false then
		mcdb = true
		script.Parent.myCarts:TweenPosition(UDim2.new(1.1,0,.2,0))
		script.Parent.myCartslabel:TweenPosition(UDim2.new(1.1,0,.135,0))
		wait(1.2)
		mcstatus = false
		mcdb = false
	end
end)

for i,v in pairs(script.Parent.myCarts:GetChildren()) do
	if v:IsA("ImageButton") then
		v.MouseButton1Down:connect(function()
			print("Working!")
		end)
	end
end

Thanks for anyone who helps me.

1 answer

You can make a function for registering the button clicks:

function checkButtonClick(button)
	button.MouseButton1Down:connect(function()
		print("Working!")
	end)
end

for i,v in pairs(script.Parent.myCarts:GetChildren()) do
    if v:IsA("ImageButton") then
        checkButtonClick(v)
    end
end

And then from then on, every time you create a new button, you can use the function to detect the clicks:

local newButton = --created button here
checkButtonClick(newButton)

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