How do I "Destroy" a prefab in Unity?

Every time I complete the puzzle I get an error thrown at me: 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.

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

public class PuzzleManagerScript : MonoBehaviour
{

public GameObject[] myPuzzles;
public GameObject activePuzzle;
public GameObject fullImage;
private GameObject currentAnimal;
public GameObject[] myPieces;

public bool allPiecesPlaced = false;
public bool puzzleComplete = false;    

// Start is called before the first frame update
void Start()
{
    GameObject activePuzzle = Instantiate(myPuzzles[0]);
    myPieces = GameObject.FindGameObjectsWithTag("PuzzlePieces");
}

// Update is called once per frame
void Update()
{
    allPiecesPlaced = true;
    for (int i=0; i < myPieces.Length; i++)
    {
        if (myPieces*.GetComponent<DragDrop>().isInPlace == false)*

{
allPiecesPlaced = false;
}
}
if (allPiecesPlaced == true && puzzleComplete == false)
{
puzzleComplete = true;
currentAnimal = Instantiate(fullImage);
Debug.Log(“Puzzle Complete”);
}
if (puzzleComplete == true)
{
GameObject[] prefabs = GameObject.FindGameObjectsWithTag(“Master”);
foreach (GameObject prefab in prefabs)
{
Destroy(prefab);
}
}
}
}

1 Answer

1

Hi,
I think when the puzzle is complete you destroy some items on line 41.
But the next frame, since the puzzle is still complete, prefabs is empty, and line 41 tries to destroy a null GameObject.
Possible solution: add a boolean prefabsAreDestroyed, and check that the prefabs are still in the game.

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

public class PuzzleManagerScript : MonoBehaviour
{

     public GameObject[] myPuzzles;
     public GameObject activePuzzle;
     public GameObject fullImage;
     private GameObject currentAnimal;
     public GameObject[] myPieces;
     public bool allPiecesPlaced = false;
     public bool puzzleComplete = false;  
     private bool prefabsAreDestroyed;

     void Start ()
     {
         GameObject activePuzzle = Instantiate(myPuzzles[0]);
         myPieces = GameObject.FindGameObjectsWithTag("PuzzlePieces");
     }

     void Update ()
     {
         allPiecesPlaced = true;
         for (int i=0; i < myPieces.Length; i++)
         {
             if (myPieces*.GetComponent<DragDrop>().isInPlace == false)*

{
allPiecesPlaced = false;
}
}
if (allPiecesPlaced == true && puzzleComplete == false)
{
puzzleComplete = true;
currentAnimal = Instantiate(fullImage);
Debug.Log(“Puzzle Complete”);
}
if (puzzleComplete == true && !prefabsAreDestroyed)
{
prefabsAreDestroyed = true;
GameObject[] prefabs = GameObject.FindGameObjectsWithTag(“Master”);
foreach (GameObject prefab in prefabs)
{
Destroy(prefab);
}
}
}