Hello everyone, how are you?
I have developed a simple inventory system with drag and drop functionality, and now I am working on a “switching” items functionality.
The main components are the Inventorymanager (manages the whole game inventory), and the inventoryslot (a UI parent component) which holds an inventoryitem (a component that holds the image in which the player can drag and drop into other slots).
My inventory has zero slots, and each time a new item enters it the inventory manager instantiates a new inventory slot.
All the drag-and-drop functionality is held within the inventory item component, which means that a new inventory item is created when a new item enters the inventory. But then something is happening. I developed an Action to ping the inventory manager when an item was dragged and dropped in place of another item, making them switch places. This way, the inventory manager can switch the items’ places in the inventory item list (I don’t know if this is necessary, but I would like to do it regardless for consistency’s sake). But every time I do it, my InventoryItem component says that the Action is null. I have tried with other simpler actions before and they all come as null.
Can anyone help me discover why they are null? Any tips on how to improve the logic/scripts are very welcome.
Inventory Manager ssubcribing to Action
public GameObject inventoryItemPrefab;
// TODO: subscribe to Item replacing action event
private void Awake()
{
inventoryItemPrefab.GetComponent<InventoryItem>().ItemWasReplaced += ReplaceItemMethod;
}
private void ReplaceItemMethod(int newIndex, int oldIndex)
{
print(newIndex);
print(oldIndex);
}
Inventory Item component Awake method with an example Action (Just to see if things are working. They are not. Even this simple example Action come as null).
public event Action exampleThingy;
private void Awake()
{
exampleThingy.Invoke();
}
Inventory Item component with OnEndDrag function for the IEndDragHandler interface (This component is instantiated every time a new item is added. Maybe that why the action is null? Since the component does not exist at the hierarchy and is instantiated later the Action simply starts as null?)
public event Action<int, int> ItemWasReplaced;
public void OnEndDrag(PointerEventData eventData)
{
if (itemToReplace != null)
{
itemToReplace.transform.SetParent(parentBeforeDrag);
itemReplaced = true;
}
itemImage.raycastTarget = true;
transform.SetParent(parentAfterDrag);
if (itemReplaced)
{
Transform parent = parentAfterDrag.parent;
InventorySlot[] childList = parent.GetComponentsInChildren<InventorySlot>();
print(ItemWasReplaced);
CallItemReplaced();
ItemWasReplaced.Invoke(ReturnFoundIndex(childList, parentAfterDrag),
ReturnFoundIndex(childList, parentBeforeDrag));
}
}
I also attatched a GIF to showcase the behaviour in game mode.