Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Get event sender in event handler (UnityAction)?

Discussion in 'UGUI & TextMesh Pro' started by CDR2003, Aug 28, 2014.

  1. CDR2003

    CDR2003

    Joined:
    Mar 4, 2014
    Posts:
    3
    I'm currently writing a custom button group. I need to add event listener when a button dynamically added in my group. And, when a button is clicked, I need to know which is clicked. How can I know the event sender when an event occurs?
     
  2. dakka

    dakka

    Joined:
    Jun 25, 2010
    Posts:
    113
    You can setup your OnClick event to return the button clicked since it is a Monobehaviour

    Code (CSharp):
    1. void OnClick(Button button)
     
  3. paradizIsCool

    paradizIsCool

    Joined:
    Jul 10, 2014
    Posts:
    177
    It doesn't use uGui event system
     
  4. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    556
    Would something like this work?

    Code (csharp):
    1. for(int i=0; i<5; i++){
    2.     Button btn = ((GameObject)Object.Instantiate(btnPrefab)).GetComponent<Button>();
    3.     btn.onClick.AddListener(delegate{Callback(btn);});
    4. }
    5.  
    6. void Callback(Button btnPressed){
    7.     Debug.Log(btnPressed.gameObject.name + " pressed!");
    8. }
     
    OMOH98 likes this.
  5. CDR2003

    CDR2003

    Joined:
    Mar 4, 2014
    Posts:
    3
    Yeah, I did come up with this solution. However, I found that if I want to remove the event listener, I have to store all the delegates in a list in order to pass them when I call RemoveListener().
     
  6. paradizIsCool

    paradizIsCool

    Joined:
    Jul 10, 2014
    Posts:
    177
    This is not always applicable but you may use RemoveAllListeners();
     
  7. CDR2003

    CDR2003

    Joined:
    Mar 4, 2014
    Posts:
    3
    You're right. But what if I only want to remove the specific listener?
     
  8. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    556
    You would have to keep track of your Listeners either way then. If you want to remove a specific Listener only, you'd need some way of telling it which to remove. An additional (if possibly convoluted) way might be to use extension methods, and keep track of your listeners by name inside an extended EventTrigger class. You might end up with something like:

    Code (csharp):
    1. btn.onClick.AddListener("ListenerName", delegate{Callback(btn);});
    2. btn.onClick.RemoveListener("ListenerName");
    And then in your overridden AddListener, simply add the delegate to a Dictionary (I forgot what they're called in C#; Hash?)

    I would, however, like to state for the record that I do not endorse this specific approach. ;)
     
    OMOH98 likes this.