How to get which instantiated prefab button is selected in a list of dozens of instantiated prefab buttons

Hello everyone,

so I have a scrollable list as an UI element and I have a prefab button. Then my main script instantiates the prefab button a couple dozen times and puts all as children to the viewport of the scrollable list. Every button has the gimmick to change color when selected. Now how would I know which button was selected by the user?

My main problem is that a script I put on the prefab wont be able to interact with the scene elements since its only a prefab and not yet instantiated. Obviously I could just iterate over all the current children of the viewport and see if any button is selected but is that the smoothest way? That would be very inefficient if the list has thousands of entries in the future…


There are multiple ways.

Are you using mouse for selection? If yes, you can raycast the mouse position to know which button is beeing selected.

Ray ray = cam.ViewportPointToRay(cam.ScreenToViewportPoint(Input.mousePosition));

Another solution is with scripts. If you have 1 “button script” in each button, and 1 “menu script” with a public variable called lastSelectedButton , you just need that the buttons send the info to the menu script that they (the button) has been selected. This way the menu script knows whats the las button that has been selected.


If anyone in the future is wondering, I found the solution. Just use a script on the prefab after it is instantiated. I added a script to it in the code right after instantiating the prefab. The script every instantiated button has is simply going to give the button to the main game logic script when the button is selected, so I always know which button is selected.