- Home /
Removing method from OnRightClickEvent
Hi,
I am making an inventory system for a 2D game. I have some functionality that runs a method when right-clicking on an "item slot".
However, sometimes I want something else to happen when right-clicking. In this case, I want to transfer items to a chest when the chest is open.
In my ItemSlot script, I listen for OnPointerClick() and check if it was a right-click:
public event Action<ItemSlot> OnRightClickEvent;
public void OnPointerClick(PointerEventData eventData)
{
if (eventData != null && eventData.button == PointerEventData.InputButton.Right)
{
if (OnRightClickEvent != null)
{
OnRightClickEvent(this);
}
}
}
In my ItemContainer (inventory) script, I set it up:
public event Action<ItemSlot> OnRightClickEvent;
protected virtual void Awake()
{
for (int i = 0; i < itemSlots.Count; i++)
{
itemSlots[i].OnRightClickEvent += slot => OnRightClickEvent(slot);
}
}
And in my InventoryManager, I assign a method that runs every time I click on an "item slot" in the inventory:
private void Awake()
{
inventory.OnRightClickEvent += InventoryRightClick;
}
private void InventoryRightClick(ItemSlot itemSlot)
{
//do something
}
Also in the same script, I sometimes run this code to switch the method I am running when a right-click occurs:
public void OpenItemContainer(ItemContainer itemContainer)
{
inventory.OnRightClickEvent -= InventoryRightClick;
inventory.OnRightClickEvent += TransferToItemContainer;
}
private void TransferToItemContainer(ItemSlot itemSlot)
{
//do something else
}
The problem is that this last part doesn't work. When I run the OpenItemContainer() method, and then proceed with right-clicking on an "item slot", I just end up running both methods.
In other words, this doesn't work:
inventory.OnRightClickEvent -= InventoryRightClick;
Does anyone know why? Thanks, in advance!