` fireAction.started += context => ` style of code, how does this work?

Ive seen code written this way before but I dont really understand how it works. This comes from the interactions section of unity’s input system documentation

var fireAction = new InputAction("fire");
fireAction.AddBinding("<Gamepad>/buttonSouth")
    // Tap fires, slow tap charges. Both act on release.
    .WithInteractions("tap,slowTap");

fireAction.started +=
    context =>
    {
        if (context.interaction is SlowTapInteraction)
            ShowChargingUI();
    };

I understand how the var fireAction = new InputAction("Fire")… works, thats just declaring the fireAction variable, its that action.started += Context =>bit that i dont really get. Is this a Unity Input system specific thing or can you do this with any kind of code (provided certain conditions of course)? I just dont know whats going on here.

Im trying to figure out the interactions with the input system, seeing as with my game, pressing the sprint key makes you dodge, but holding it makes you sprint, so im trying to figure out the Input system seeing as it feels like the “recommended” way, even though i could probably just code this in and skip the whole ‘interactions’ part of the input system.

It’s called an anonymous function: Lambda expressions - Lambda expressions and anonymous functions - C# reference | Microsoft Learn

Effectively it’s a lot of syntax sugar. You can get the same result by registering a method with the correct parameter:

private void OnFireActionStarted(InputAction.CallbackContext ctx) { ... }

fireAction.started += OnFireActionStarted;

Note you’ll want to do this method if you ever want to unsubscribe from delegates, as you can’t easily do that with anonymous functions.

Okay, well that makes sense. Its kind of just a shorthand method.

That being said,

I dont really know, fully, what delegates are. From what im understanding from the learn.microsoft section on them (and a little test I did), it looks kind of like a way to call multiple methods from invoking a single line, so if you wanted two different actions to happen from one line, you could use delegates. Am I correct in this?

I think ill just avoid the anonymous function thing. I think they look a little messy.

Delegates - otherwise known as a callback - are objects that can store references to one or more methods.

You use them to let other objects know when something has happened, without having to know what those objects are (or if there are any at all).

And you hook into them when you want to know when something has happened. Such as with the InputAction.started, .performed and .cancelled callbacks letting you listen to when an input has done either of those three things.