[C#] Working with AddListener

I have been searching for the answer but not been able to find it so i ask here.

Could someone please explain to me why this works:

// ADD LISTENER SO IT REACT TO CLICKS
            newItem.GetComponent<Button>().onClick.AddListener(() =>
                                        {print ("GET: " + newItem.GetComponentInChildren<Text>().text);});

But not this:

// ADD LISTENER SO IT REACT TO CLICKS
            newItem.GetComponent<Button>().onClick.AddListener(() =>  {DoThis();});


===

void DoThis() {
    print ("GET: " + newItem.GetComponentInChildren<Text>().text);
}

And if there is a good way to accomplish that?

Thanks in advance :slight_smile:

try this:

newItem.GetComponent<Button> ().onClick.AddListener (delegate {
DoThis ();});


public void DoThis() {
}

@fire7side a BIG thank you :slight_smile:

this also works

newItem.GetComponent<Button>().onClick.AddListener(DoThis);

Don’t forget to remove the listener.

May i ask why and when?

I am afraid not ?

Typically there is no need to remove a listener, it will be cleaned up automatically when the button is destroyed. Unless of course you want to change the listener.

I suppose it depends on the complexity of his UI, but its probably good practice to do so anyway.

it does work.
old mono may not compile it but unity does and visual studio (which now has a real free version) also does
i think it is a new feature that was recently added
http://csharpsimple.blogspot.ca/2012/01/what-is-method-group.html