Search Unity

Send additional parameters to callback

Discussion in 'UI Toolkit' started by rogerdv, Nov 13, 2019.

  1. rogerdv

    rogerdv

    Joined:
    Jul 16, 2012
    Posts:
    90
    Is there some way to send an additional parameter to a callback, or at least, get the name of the button or element that originated the event?
     
  2. AlexandreT-unity

    AlexandreT-unity

    Unity Technologies

    Joined:
    Feb 1, 2018
    Posts:
    377
    Try the following:
    Code (CSharp):
    1. static void OnMouseUp(MouseUpEvent evt, Whatever we)
    2. {
    3.     // Do stuff.
    4. }
    5.  
    6. void RegisterToElement(VisualElement ve, Whatever we)
    7. {
    8.     ve.RegisterCallback<MouseUpEvent, Whatever>(OnMouseUp, we);
    9. }
     
    orenwang likes this.
  3. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    1,231
    All events have a target parameter that contains the element where the event originated from:

    Code (CSharp):
    1. void OnMouseUp(MouseUpEvent evt) {
    2.     var button = evt.target as Button;
    3.     ...
    4. }
    and Button specifically has an overload for its callback that takes an event as an argument:
    Code (CSharp):
    1. var button = new Button();
    2. button.clickable.clickedWithEventInfo += (evt) => Debug.Log((evt.target as Button).name);
     
    squigglebucket likes this.