I am trying to create an Inventory which fills after gathering items like Coins etc.
My problem is that whenever I Destroy() the GameObject of the coin after adding it to an Array in my Inventory Component it will also miss the reference to the stored GameObject in the Array.
//Add Item to the First free Slot in the Inventory
//Overload 1: Add Item to a Specific slot in the Inventory
function AddItem(item:GameObject, slot:int):void
//Check if there is a Item in that Specific Slot already
if(slot >= 0 && itemSlots[slot] == null)
itemSlots[slot] = item;
print("Inventory: The Inventory now contains: " + itemSlots[slot].GetComponent(ObtainableItem).itemName);
I am currently working on a solution to the exact same problem. The way I accomplished it is to have the GameObject I am destroying contain a member variable of a custom class I created that stores all of the information about that object. This may include the name of the object, name of the prefab used and any other information I may need. Also instead of using an array or list I created an Inventory script that has this member
Dictionary<System.Guid, InventoryItem> _inventory;
that I can use to store the item information for later reference such as re-creating the object I have previously destroyed. Using System.Guid as the key means I don’t have to spend time maintaining the list and I can have an unlimited number of instances of the same or different objects. This Dictionary can further be used in a InventoyGUI script that displays the items to the player for selection.
for those who are curious how I solved it:
I set both the renderer and the collider to false (invisible and i cant collide with it anymore)
this.gameObject.renderer.enabled = false;
this.gameObject.GetComponent(Collider).enabled = false;
Thats not really resource saving but yeah it works. I might optimize it later on