Search Unity

How to register Mouse Events for a Button

Discussion in 'UIElements' started by fxlange, Jan 20, 2019.

  1. fxlange

    fxlange

    Joined:
    Dec 20, 2016
    Posts:
    6
    Hi there,

    I'm trying to register callbacks for mouse events for a UIElements.Button. For example:

    Code (CSharp):
    1. Button button = new Button();
    2. button.RegisterCallback<MouseDownEvent>(e=>Debug.Log("button pressed"));
    This is not working - I'm assuming because this normal callback behavior is somehow overridden for Buttons via the Clickable Manipulator. In the examples you have to assign your callback via the constructor - which is fine and looks handy.

    Code (CSharp):
    1. var button = new Button(()=>Debug.Log("button clicked")) { text = "MY BUTTON" };

    But how to assign a callback for a button created via uxml? For example:

    var button= uxml.Q<Button>("myButton");



    I tried assigning a new Clickable in different ways but also without success.

    Thanks in advance.

    Best,
    Felix
     
  2. Rocktavious

    Rocktavious

    Joined:
    May 10, 2017
    Posts:
    41
    unity_uBWrVSOSbMFI6Q likes this.
  3. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    460
    You can give the Button a callback after construction (via UXML for example) by assigning you callback to:
    Code (CSharp):
    1. myButton.clickable.clicked += myCallback;
     
  4. fxlange

    fxlange

    Joined:
    Dec 20, 2016
    Posts:
    6
    thanks a lot @uDamian - that works.
     
  5. deus0

    deus0

    Joined:
    May 12, 2015
    Posts:
    18
    Hey, how to also invoke this clicked event? Trying to setup gamepad navigation for it.

    Wait nevermind, i figured it out eventually. Using reflection:

    Code (CSharp):
    1.  
    2.                 Clickable clickable = button.clickable;
    3.                 MouseDownEvent mouseDownEvent = MouseDownEvent.GetPooled();
    4.                 //clickable.Invoke();
    5.                 MethodInfo dynMethod = clickable.GetType().GetMethod("Invoke",
    6.                 BindingFlags.NonPublic | BindingFlags.Instance);
    7.                 dynMethod.Invoke(clickable, new object[] { mouseDownEvent });
    8.                 mouseDownEvent.Dispose();
    9.  
     
    Last edited: Dec 29, 2019
unityunity