Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Distinguishing between buttons in a single OnClick() delegate

Discussion in 'UGUI & TextMesh Pro' started by zasulon, Feb 15, 2024.

  1. zasulon

    zasulon

    Joined:
    Apr 5, 2022
    Posts:
    2
    I'm using multiple TextMeshPro buttons and can assign an OnClick() handler method to each button individually. Is it also possible to have one OnClick() method for multiple buttons that can then somehow distinguish which button was pressed. This would e.g. be possible if there was the button reference parameter in the OnClick() from which the click came, but I could not find any information that this is possible.
     
  2. JuliaP_Unity

    JuliaP_Unity

    Unity Technologies

    Joined:
    Mar 26, 2020
    Posts:
    705
    You can just give a parameter to your OnClick() method declaration and a field for assigning something to that parameter shows up on your OnClick() assignment for the button.
     
  3. zasulon

    zasulon

    Joined:
    Apr 5, 2022
    Posts:
    2
    Ah, nice, thank you!
    I had not noticed before that a parameter shows up in the inspector when I assign a method with a parameter to the Button OnClick() field.

    Also, I have found this piece of code that helps when creating buttons programmatically:
    for(int i = 0; i < 10; i++) {
    ...
    button.onClick.AddListener(delegate () { ButtonPressed(i); });
    }