# How to Destroy an Instance of a Prefab Without Removing the Prefab?

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:

As the game is running:

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?

• 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? – Sean Carey May 2 '19 at 2:07
• @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. – DMGregory May 2 '19 at 2:13