Search code examples
c#unity-game-engineonclickonclicklistenereventtrigger

How to access Dynamic BaseEventData from C# script using EventTrigger, Unity?


I have a code here, where I want to call a function when a pointer click happens.

EventTrigger trigger = instance.AddComponent<EventTrigger>();
var pointerClick = new EventTrigger.Entry();
pointerClick.eventID = EventTriggerType.PointerClick;
pointerClick.callback.AddListener(delegate { UIController.Click(???); });
trigger.triggers.Add(pointerClick);

Now, I want to know if the click was a left or right one.
Code from this thread: https://forum.unity.com/threads/how-to-detect-handle-right-click.355146/

public void Click(BaseEventData bed)
{
        PointerEventData ped = (PointerEventData)bed;
        Debug.Log("Button: " + ped.pointerId);

        // pointerId will be -1 for left mouse button, -2 for right
}

(Based on the result I have to call other methods - it is just not important here.)

The problem is that I don't know how to give the BaseEventData argument input for the function.
I know, in the inspector there is Dynamic BaseEventData but in script?

What to feed as the argument input (BaseEventData bed for Click())?

Thanks for your help!


Solution

  • You can declare UIController.Click as follows:

    public void Click( BaseEventData bed )
    {
        // ...
    }
    

    Then: pointerClick.callback.AddListener( UIController.Click );

    To determine the clicked button, use PointerEventData's button property, NOT pointerId property:

    if( ped.button == PointerEventData.InputButton.Left )
    {
        // Left clicked
    }