- Home /
How do I save a gameObject to a list so i can destroy in the scene?
I am trying to create an inventory system and when I add a weapon to the player, I remove the weapon from the inventory list and try to add the weapon that is currently equipped to the inventory list:
if(port1.transform.childCount > 0)
{
GameObject obj = port1.transform.GetChild(0).gameObject;
inventoryWeapons.Add(obj);
Destroy( port1.transform.GetChild(0).gameObject);
}
GameObject weap = (GameObject) Instantiate(itemToEquipt);
weap.transform.parent = port1.transform;
weap.transform.localPosition = Vector3.zero;
weap.transform.localRotation = Quaternion.identity;
inventoryWeapons.Remove(itemToEquipt);
itemToEquipt =null;
I get an error that the gameobject was destroyed and I'm still trying to access it. is there a way I can save an instance of the weapon previously attached without keeping it in the scene? the weapon gameobject has information I want to preserve (damage/accuracy/etc).
If your destroy the gameObject, then it is destroyed. Why destroy it and then see$$anonymous$$gly reinstantiate it?
Answer by Bunny83 · Mar 31, 2014 at 02:26 AM
The answer is: No! You can't "store" a GameObject somewhere else then in the scene. The only exception are prefabs. They are instances but not in the scene, but prefabs can't be created at runtime. You have to keep the object in your scene. Just disable it with SetActive(false).
That's what I'm trying now, but what I want is to have 3(or more) weapon ports and have the weapon moved to the port selected.
I am right now creating the objects physically inside the "loot" object and then making a part of the player its new parent when picked up, then when equipped, the port become the parent.
haven't had time to test this system, but I can't see why it shouldn't work... right now.
Sure, parenting the picked-up objects to the player is the usual way. You could also have an empty gameobject as child of your player object (lets call it "backpack") and parent all picked-up objects to this container object. That way you can simply deactivate the container and all childs are disabled as well. Also the objects don't clutter other active parts of the model.
Since you store a reference in your list you have easy access to the objects inside the "backpack".