I'm making a simple runner game where obstacles spawn off in the distance and move towards the player. I want to remove them after they're invisible to the player.

I made an Obstacle prefab and a SpawnObstacles.cs script, which I added to an empty game object. In it, I call

Instantiate(obstaclePrefab, xLocation, yLocation, zLocation, Quaternion.identity);

a set number of times per second.

In the Update() method of the obstacle prefab, I have

if (transform.position.z < -20){ GameObject.Destroy(gameObject); }

so each obstacle will destroy itself automatically.

When I run the game, I get a:

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.

error on the Instantiate call in SpawnObstacles.cs

Before the game starts:

enter image description here

As the game is running:

enter image description here

How can I have a single instance of a prefab destroy itself without destroying the entire prefab? I think I need the obstacles to be inside the Obstacle Prefab. Perhaps I could loop through all obstacles and delete the ones invisible to the player?

  • 1
    \$\begingroup\$ I think the problem is that your SpawnObstacles script is referencing a obstacle that exists as an active gameobject in the scene, when in fact it should be referencing that object as a prefab. Do you know what I mean? Before your game runs, before you get a chance to spawn any obstacles, are there already any obstacles in your scene? \$\endgroup\$
    – Sean Carey
    May 2, 2019 at 2:07
  • \$\begingroup\$ @SeanCarey this looks like it could be a good answer, especially if you include a screenshot or two to illustrate the difference between a prefab in the project folder vs an instance in the scene. \$\endgroup\$
    – DMGregory
    May 2, 2019 at 2:13

1 Answer 1


Your SpawnObstacles script is referencing a gameObject in the scene, rather than an actual prefab. To create a prefab, drag and drop your Obstacles object to your assets folder. Then make sure that your SpawnObstacles script is referencing that prefab, rather than the gameObject itself. enter image description here

  • \$\begingroup\$ Thanks, this worked. I also had to add "player = GameObject.Find("Player")" inside the Obstacle Prefab's Start() method since you can't reference game objects (from the inspector) in a prefab. \$\endgroup\$
    – user128106
    May 2, 2019 at 22:07
  • 1
    \$\begingroup\$ @GreenPlasma Rather than that, assign the "Player" tag to your Player object, and use FindGameObjectWithTag. Searching through the tags is usually faster than searching through all of the objects, because there aren't as many tags as there are objects. Also, keep in mind that when you use GameObject.Find, your not just searching all of the objects, but also their children, grandchildren, etc... \$\endgroup\$
    – Sean Carey
    May 3, 2019 at 4:12

You must log in to answer this question.