- Home /
Instantiating prefabs: "The object of type GameObject has been destroyed".
I am using this code to equip items on the player:
//Equipping items on the character's model
public void EquipItems()
{
//runs through each location where the items will be equipped on the player character model
for (int i = 0; i < 5; i++)
{
//if the equip location exists
if (itemLocation [i] != null)
{
//destroys any existing equipped items if they don't match the newly-equipped items
foreach (Transform child in itemLocation[i].transform)
{
if (child != null)
{
if (child.gameObject.name != equippedItems[i].itemPrefab.name && child.gameObject.tag == "Item")
{
GameObject.Destroy(child.gameObject);
}
}
}
//places the new items in their locations
equippedItemsClones[i] = Instantiate (equippedItems [i].itemPrefab, itemLocation[i].transform.position, itemLocation[i].transform.rotation) as GameObject;
equippedItemsClones[i].transform.parent = itemLocation[i].transform;
Debug.Log("instantiating " + equippedItems[i].itemName);
}
}
}
But, when I run it, I pick up an item from the ground, try to equip it, and get shown this error message:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineObject.cs:74) UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineObject.cs:84) CharacterClass.EquipItems () (at Assets/scripts/Classes/CharacterClass.cs:94) InventoryScript.Update () (at Assets/scripts/GUIScripts/InventoryScripts/InventoryScript.cs:63)
I don't know what's gone wrong.
Please tell us what is line 63 of the script InventoryScript.cs because we don't know where it is if you post only a fraction of the code.
But since you check intemLocation[i], I assume that it is equippedItems[i] that has a problem...
Answer by Tehnique · Aug 05, 2014 at 09:50 AM
Most probably, your list of equipedItems is populated based on references to the transform children that are tagged as items. You then go and destroy some of those children, and then try to access them again from equipedItems, but since equipedItems are references, and the referenced object was destroyed, you get that error.
Either instantiate your clones, and then call Destroy, or check that equipedItems[i] is != null before instantiating.