How do I tell which button was clicked, if I'm using a single function for many buttons?

I’m adding a load of buttons to the UI dynamically. I need to know which one’s been clicked, but there doesn’t seem to be anything useful in what I’m being passed.

This is a local script in my GUI. It happens to create two buttons at the moment, because that’s how many levels I’ve created for my game

local playerGUI = game:GetService('Players').LocalPlayer:WaitForChild('PlayerGui')
local ReplicatedStorage = game:GetService("ReplicatedStorage")

function onButtonActivated(inputObject, clickCount)
	print(inputObject.Name)
end

local getLevelNames = ReplicatedStorage:WaitForChild("GetLevelNames")
local levelNames = getLevelNames:InvokeServer()
for i,levelName in ipairs(levelNames) do
	print(levelName)
	
	local button = Instance.new("TextButton",playerGUI.DebugGUI)
	button.Name = levelName
	button.Text = levelName
	button.Size = UDim2.new(0, 200, 0, 20)
	button.Position = UDim2.new(0, 0, 1, -i*40)
	
	button.Activated:Connect(onButtonActivated)
end

GetLevelNames returns an array of strings. The buttons go on the screen, they’re clickable, and I get a print when I click them.

2 Likes

Just wanted to say, this goes in #help-and-feedback:scripting-support

You can’t natively, but you could just wrap the function in an anonymous function and pass the button as an argument. Quick example:

function onButtonActivated(button, inputObject, clickCount) -- add button as an argument
	-- whatever
end

-- aside from that, all the same code until button.Activated
button.Activated:Connect(function(...)
	onButtonActivated(button, ...)
end)
4 Likes