Rohan Mayya
Rohan Mayya

Reputation: 206

C# add extra parameter in the handler of an event

In C#/Unity, is there a way to pass more arguments to an event handler that were not specified in the delegate?

Assume that I cannot modify the delegate. (It comes from an external class.)

I need to be able to do this so I can unsubscribe from my handler later (onClick -= HandleClick somewhere else in the code).

Example:

delegate void A(str s);

event A onClick;

Awake() {
 onClick += HandleClick;
}

void HandleOnClick(str s, int a) {
   // How to get access to this second argument a here?
}

I know I can do the following:

int a = 10;
onClick += (s) => HandleOnClick(s, 10);

But this won't let me unregister the lambda (since it's an anonymous delegate) if I wire it up this way.

Upvotes: 1

Views: 271

Answers (1)

D-Shih
D-Shih

Reputation: 46229

One way you can try to use a variable to hold the delegate reference which is able to subscribe or unsubscribe from the event.

Awake() {
  int a = 10;
  var e1 = (s) => HandleOnClick(s, a);
  onClick += e1;
 
  onClick -= e1;
}

Upvotes: 1

Related Questions