Hi,
I’ve created 16 buttons that can be selected by the user to represent the maximum number of players they want in a game. The text of each button is set to the number of players that it represents.
I’m using buttons as they have all the necessary styling options by default, rather than trying to override the default toggle element. As Buttons do not have a ‘selected’ tag I’ll need to set their USS class in code once they are clicked.
It seems really inefficient to explicitly map each button to a variable in my class and then add a clicked event for each one. I would like to just do a root.Q() to retrieve them all then loop through them and point them all to the same eventhandler. However I need to be able to pass the calling button through to the handler so that I can retrieve it’s text property.
button.clicked doesn’t seem to have any options to pass the sender through. Is there a better method?
If anyone else wants to do this, you can use the clickable.clickedWithEventInfo event:
This allows me to loop through my 16 buttons and create an event that reads the buttons text and sticks that in a variable. This avoids having to create 16 button variables and 16 different click handlers.
void OnGeometryChange(GeometryChangedEvent evt)
{
// Get all buttons
var buttons = this.Query<Button>(null, "number-button");
// Iterate through buttons
buttons.ForEach(SetupButton);
this.UnregisterCallback<GeometryChangedEvent>(OnGeometryChange);
}
#endregion
private void SetupButton(Button button)
{
//Subscribe to the clickedWithEventInfo event
button.clickable.clickedWithEventInfo += Clickable_clickedWithEventInfo;
}
private void Clickable_clickedWithEventInfo(EventBase obj)
{
// Cast the target to a Button type
var button = (Button)obj.target;
// I'm setting this button to have focus (this invokes the #my-button:focus state from my USS)
button.Focus();
// Grab the value of the button's text field
m_MaxPlayers = Convert.ToInt32(button.text);
}
2 Likes