Prefab immediately destroys after instantiation


I am extremely new to programming, so I’m probably making a lot of rookie mistakes. I seem to have two major problems.

First problem, I am trying to spawn my Sheep prefab every two seconds. I comment out the collision detection method because I know there’s something wrong there as well. I press run and it waits two seconds to spawn the first one as expected. But then it keeps spawning them really fast instead of waiting another two seconds.

The second problem is with the collision method. I made the prefab destroy itself upon collision with an object with the Obstacle tag. It instantly destroys the new sheep that spawn. I tried deleting everything in the level except the ground plane and it still detects collision. The ground does not have the Obstacle tag. Why is it detecting collision even though the sheep are not colliding with anything?

Also, why do I have to place a sheep in the level in order for it to spawn sheep? It doesn’t spawn unless I place one manually in the scene.

public GameObject sheep;

private Vector3 spawnPosition = new Vector3(-2f, 0.5f, -2f);
private float spawnRate = 2f;
private float nextSpawn = 2f;

// Update is called once per frame
void Update () {

	//Spawn sheep at rate of spawnRate
	if(Time.time > nextSpawn)
		nextSpawn = Time.time + spawnRate;
		Instantiate(sheep, spawnPosition, Quaternion.Euler (0, 90, 0));
		Debug.Log ("Sheep spawned");

//Collision detection
void OnCollisionEnter(Collision col) {
	if(col.gameObject.tag == "Obstacle") {
		Debug.Log("Collision with Obstacle detected");


Is this script attached to your prefab? I assume it is based on your calling Destroy() on transform.gameObject.

If it is, then once you’ve instantiated one sheep, that one sheep will also take a look at Time.time and see that it’s larger than nextSpawn and spawn a sheep which will do the same thing ad infinitum. You want your instantiation script on its own GameObject, entirely unconnected to the sheep in this case. That GameObject needs to be active in the scene in order to run Update().

That’s also why you have to place a sheep in the level. That script is attached to your sheep, it’s not going to be run until a sheep is in the level.

As for the collisions, are your sheep tagged with “Obstacle” themselves? If so, they’re colliding with eachother.