Add Component to List and then Destroy GameObject is okay?

Hello!

I wrote this code for a simple inventory, and I’m surprised not to be getting a crash or a null anywhere. In the OnTriggerEnter() function, I first add the component to my list, and then destroy the gameObject it was attached to. I read that Destroy() also destroys all the components, and since GetComponent() returns a reference to the component, it seems like when I try to access the inventoryItems later (in the Update), it should crash. But it works fine! Anyone know why?

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Inventory : MonoBehaviour {
List items = new List();

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
	if (Input.GetKeyDown("space"))
	{
		Debug.Log("Inventory contents:");
		foreach (InventoryItem item in items)
		{
			Debug.Log(item.itemName);
		}
	}
}

void OnTriggerEnter(Collider other) {
	InventoryItem item = other.gameObject.GetComponent<InventoryItem>();
	if (item != null)
	{
		items.Add(item);
		Destroy(other.gameObject);
	}
}

}

Yes the Destroy() command destroys the gameobject in the immediate scene and hierarchy, but not in the prefabs. So when you use getcomponent<>() you’re actually getting another instance of this gameobject from the prefabs.

Take a bullets and pistol script for example: when the player shoots a bullet is called from the prefabs into the scene, then is destroyed either after some time or when it collides. When the player shoots again the instance is repeated and so on and so on… Hope this helps.

You’re seeing weird behaviour because you’re using Components in an unsupported way (i.e. trying to keep references to them when they’re not attached to a GameObject). And while checking the itemName field seems to work fine, I’d say this seems to be more of a glitch than anything else. You’ll find that if you evaluate “item == null” the result will be true, and if you try to access “item.gameObject” you’ll actually get a runtime error saying the object (meaning the item itself, not the gameObject) was destroyed.

My recommendation would be: don’t try and use components themselves as inventory items. You could instead use a ScriptableObject which has a reference to the item prefab. You can then create/destroy the prefab representing the item in the world whenever it’s dropped or picked up, while using the reference to the scriptableobject instance as the ‘true’ item which can be added to inventory/chests and passed around whether it needs a real-world visual representation or not.