How do I make my table detect which clickdetector got pressed?

Howdy, I am trying to make a door with a code and I am trying to write my code as neatly and versatile as possible for the game. The issue is that I have a few buttons each with a click detector and I don’t want to write out a function for each of the buttons in the script. So I figured I would approach the solution by inserting the ClickDetector into a table in my script. The problem is I don’t know how to make my script detect which ClickDetector was pushed in the table without copy and pasting a function for each individual ClickDetector.

Here is my Script:

local CodeColors = {"Green","Blue","Red","Yellow"} -- The values the code will be made out of.
local DoorCode = {} -- The code the players need to crack.
local CurrentCode = {} -- The code the players typed in.
local DoorDifficulty = 2 -- How many digits are in the code.
local ButtonTable = {}  -- Table filled with click detectors of each of the buttons.

for i,v in pairs(script.Parent.Buttons:GetChildren()) do  -- Buttons is just a folder with parts that have a click detector inside of them.
	table.insert(ButtonTable,i,v.ClickDetector) --Inserts the ClickDetectors into ButtonTable
	print(ButtonTable[i])
end

for i = 1,DoorDifficulty do  -- Just creates a random code for players to try and crack
	table.insert(DoorCode,i,CodeColors[math.random(#CodeColors)])
	print(DoorCode[i])
end

--Not sure how to make a simple function to detect which click detector has been pressed.



Here is the workspace and hierarchy of the door
image

If any of you have an idea for a solution that would be fantastic.
This is one of my first formal posts on the devforums :+1:

4 Likes

have you tried

for i, v in pairs(script.Parent.Buttons:GetChildren()) do
     v.MouseClick:Connect(function()
          -- stuff
          -- v will be the click detector
     end
end
3 Likes

I’ll be sure to try it out, i’ll get back to you if it answers the mail. Thanks!

Edit: It works, I had to edit a few things but it’s exactly what I wanted. Thank you so much!
It’s been a few months since I last scripted anything so I appreciate you for your kindness!

4 Likes