- Home /
Destroy Item Visuals but store a version of it
Hi guys. 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.
Code:
collision.gameObject.GetComponent(Inventory).AddItem(this.gameObject);
Destroy(this.gameObject);
//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):void
{
AddItem(item,GetFirstFreeItemSlot());
}
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);
}
}
Answer by doublethink · Jan 16, 2013 at 10:01 PM
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.
Thank you for your reply but I dont seem to be able to make your suggested solution work in my Project. isn't there any way to destroy the item without deleting reference to it in the variable? in other words storing a full copy of the given GameObject in it in my variables rather than linking to it
Answer by Mijdax · Jan 20, 2013 at 08:29 PM
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
Your answer
Follow this Question
Related Questions
Best approach in making Inventory UseItem functionality. 1 Answer
Placing a gameObject into, and pulling out of inventory 2 Answers
Best Way to do Regular Items and Weapons/Intractable/Special Items. 1 Answer
Cannot convert from 'int' to 'PlayFab.ClientModels.ItemInstance' 1 Answer
Trying to make a simple inventory: 0 Answers