Any way to subscribe a variable to an event?

Hi all -

I’ve an event in one class and a listener in the other. The Sender class transmits an event with an integer value which the Receiver class will need to store and do something with. Is there a way to set the value of the variable in the listener to the value transmitted via the event without first creating a method to subscribe to the event?

For example, instead of:

public class Receiver : Monobehaviour {

int value;

void Start ()
{
SenderClass.Event += ChangeValue;
}

void ChangeValue(int amount);
{
value = amount;
}

}

I’d like something to the effect of:

public class Receiver : Monobehaviour {

int value;

void Start()
{
SenderClass.Event += value;
}

}

Essentially, is there a way around having to create a method to change the variable the value of which is arriving from the outside via an event? Creating such one-off methods feels a bit, well, redundant.

Not exactly, but you can use an anonymous delegate or lambda expression.
For example:

void Start() {
   SenderClass.Event += () => value++; // always only adds 1
// or ..
   SenderClass.Event += n => value+=n;
// anonymous delegate
   SenderClass.Event += delegate { value++ };
// or...
   SenderClass.Event += delegate(int n){ value += n; };

Added notes: for small, simple things this can be kinda convenient. If the method gets long, as you might imagine it might start to look a bit odd, but to each their own.
Also, if you want to remove an event at any time, this may or may not work :slight_smile:

best you could do is a lambda expression

public class Receiver : Monobehaviour {
    int value;
    void Start() {
        SenderClass.Event += (amount) => value = amount;
    }
}

keep in mind if you do it this way, you have no way to easily unsubscribe from the event.