Bind OnHovered event to ALL buttons

I’m currently working on creating a level select screen and the widget it uses, has a button per level (obviously, clicking a button opens the corresponding level). I’ve got it set up so that each of the buttons’ properties are dynamically added, such as Image. The widget also has a Border element wrapping the Canvas Panel so that I can apply an image to the background as well.

What I’m trying to do (which I can probably do manually) is change the background image dependent on which button has been hovered over. So for example, there are 3 buttons each with a screenshot of the level, ImageA, ImageB, ImageC respectively, when hovering over the first button, the BG should change to ImageA and when hovering over the second button it should change to ImageB. For this to happen I need to bind an OnHovered event to each of the buttons. While I can do this manually, if I have 100 levels, I’d have to bind 100 buttons.

First instinct was to loop through an array of my button refs and assign OnHovered to each one there but that just overwrites the reference of the previous binding so hovering over any of the buttons, will always reference the last one - Example.

Any help on getting this working would be appreciated.

Thanks

Actually you are doing it quite right with the binding, but in your example you are getting the last reference that came from ForEach cycle.

What you actually want is to create custom dispatcher inside your button widget, that would return button’s reference (or probably image ref) and bind to this custom dispatcher, thus every binded event would have the needed ref right from event.

Edit: Ofcourse I assume each button is a separate widget created by you, and not just a default button

Ah man, thanks for the help. I had them set up as the default buttons but instead I changed it to be an individual custom button widget as per your suggestion and inside my main LevelSelect widget, I just add my LevelButton widget 3 times.

Now inside LevelButton I’ve bound the OnHovered Event so naturally, each LevelButton will have it’s own OnHovered Event - perfect. All I did then was create a custom event in LevelSelect that will get called everytime a button has been hovered over and then I can do my stuff.

LevelButton
LevelSelect

Thanks for your help!!