How do I unregister a InputAction.performed ?

I am doing an inventory system controlled with keyboard (no mouse) and I’m implementing a drop/remove item function.
When I select an inventory slot it gathers the slot infos (location, item inside, etc.)
When I deselect of course I clear the variables
I’m using the new input system, I’ve set up a key (DELETE) for that function, the thing is that every time I select a button, I’m adding the performed event, and so all the slots I’ve been on will be deleted, cause I’m not unsubscribing the event.
The code is this:

public void OnSelect(GameObject obj)
    {
        selectedItem.destinationObj = obj;
        if (itemsDisplayed.ContainsKey(obj))
            selectedItem.destinationItem = itemsDisplayed[obj];

        inputInventory.InventoryUInavigation.Drop.performed += ctx => inventory.RemoveItem(itemsDisplayed[obj].item);
    }
    public void OnDeselect(GameObject obj)
    {
        selectedItem.destinationObj = null;
        selectedItem.destinationItem = null;
    }

As you can see, I have this method called RemoveItem that needs a variable to pass, which is the slot I’m on. I have seen that you can unsubscribe if you write something like this:

public void Drop(InputAction.CallbackContext context)
    {
        // Do things
    }

and then

inputInventory.InventoryUInavigation.Drop.performed += Drop;

inputInventory.InventoryUInavigation.Drop.performed -= Drop;

But I need to pass a variable on that method, and with this I can’t do it. Please help me

you need

void FunctionName(UnityEngine.InputSystem.InputAction.CallbackContext obj){


}

Yeah but I can’t pass my GameObject argument with that

Hmm, can’t you just do … ?

void FunctionName(UnityEngine.InputSystem.InputAction.CallbackContext obj, GameObject yourObj){

}

Unfortunately I already tried and no, it doesn’t work…

EDIT: I solved it, tomorrow I’ll post the code if someone ever needs this.

public Action<InputAction.CallbackContext> handler;

void Drop (InputAction.CallbackContext ctx, GameObject obj)
    {
        // This is the method called when you subscribe to handler's event
        inventory.RemoveItem(itemsDisplayed[obj].item);
    }

    public void OnSelect(GameObject obj)
    {
        selectedItem.destinationObj = obj;
        if (itemsDisplayed.ContainsKey(obj))
            selectedItem.destinationItem = itemsDisplayed[obj];
       
        handler = (InputAction.CallbackContext ctx) => Drop(ctx, obj);

        inputInventory.InventoryUInavigation.Drop.performed += handler;
    }
    public void OnDeselect(GameObject obj)
    {
        selectedItem.destinationObj = null;
        selectedItem.destinationItem = null;
        inputInventory.InventoryUInavigation.Drop.performed -= handler;
    }

That’s how I solved it.

3 Likes