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

How do you put extra parameters in events?

I am trying to make a list of buttons that all need to execute the same general thing but with slightly different names, cost, among other data. I'm not sure how to put in extra parameters other than who triggered it without writing separate functions. For example:

function onclick(player,GuiObject) -- How can you get the GuiObject
	print(player.. " clicked ".. GuiObject)
end
GuiObject.MouseButton1Click:Connect(onclick)

How would I get the GuiObject without writing a function for each event?

1 answer

✓ Accepted answer

You can use a table with the list of buttons and use a for loop to create events for all of them. For example, you can do something like this

local player = game.Players.LocalPlayer
local buttons = {
	-- insert button1,
	-- insert button2,
	-- insert button3,
	-- insert other buttons,
}

function ButtonClicked(button_clicked)
	print(player.Name .. " clicked " .. button_clicked.Name)
	if button_clicked == buttons[1] then
		-- insert code when button 1 pressed
	elseif button_clicked == buttons[2] then
		-- insert code when button 2 pressed
	elseif button_clicked == buttons[3] then
		-- insert code when button 3 pressed
		-- do this for what you want the buttons to do
	end
end

for i,v in pairs(buttons) do
	v.MouseButton1Down:connect(function()
		ButtonClicked(v)
	end)
end

4 comments

0

Someone had the same question yesterday if you want some more info about it  https://scriptinghelpers.org/questions/90481/how-does-this-function-keep-passing-a-nil-value#83843

0

Wait can an in pairs loop connect events all at once? Won't that disable the connection?

0

in pairs loop is just a for loop but for feasibility with objects in a table. all of them will have the same event and no, it does not disable the connections.

0

Thank you, this really simplifies the code I have to write.

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