Subscribe to event with Lambda expression?

Im not sure if I understand the entire idea correctly. So in the new course (2d topdown combat RPG) we have a way to control Sword swing by mouse click. This is handled by the new input system, we create mouseclick event, and we subscribe to Event invoked by the Input System class in out code, like this:

private void Start()
    {
        playerControls.Combat.Attack.started += _ => Attack();
    }

Why do we even use lambda expression here, and not “normal” subscription to event? So far I understand, that we use the lambda expression to kinda strip the callback context from the event, because we just don’t need it, but this seems quite strange.

Another question is - how do we unsubscribe? According to the C# documentation:

You cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, go back to the code where you subscribe to the event, store the anonymous function in a delegate variable, and then add the delegate to the event. We recommend that you don’t use anonymous functions to subscribe to events if you have to unsubscribe from the event at some later point in your code.

Do we just take for granted that the sword will never be destroyed? (But as a matter of fact, there will be times, where we don’t use the sword, so I think it would make sense to unsubscribe from that event.)

Or do I miss the point entirely and this is some different system with similar syntax?

1 Like

A lambda is just a function. I guess it’s used because ‘we can’.

You don’t need a lambda for that, you can do the same thing with a normal function

private void AttackHandler(InputContext _) // I can't remember what the actual parameter type is
{
    Attack();
}

You can’t.

I don’t have this course so i can’t give you more detail as to why these things are what they are. Just how these things work in C#

1 Like

Thanks a lot. Thanks for clarification about lambda, that’s what I needed. So my guess would be its used here because “we can” and because it is simple.

What is important is feedback that I’m not lost in my understanding of things, and Im probably on the right track :slight_smile:

How things work in C# and Unity is for me more important than how they work in this particular course. (This would be also good to know too, but I think it might get clearer in the future lectures.) Also I have a slight feeling that this particular course does not really aim for best coding practices and strict SOLID programming. But it might be a valuable lesson and important step in game dev journey to learn how do do things efficiently and in a little easier and faster way than with following all the “strict rules”, especially when one (as myself) is not very proficient in coding.

Thanks for your help!

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms