How to destroy intiated gameobject prefab from controller script

Hi,

I have empty game object with a prefab controller script attached.
The script is used to instantiate a prefab in the scene in random positions after every few seconds.
I want to destroy that prefab if no interaction is made to it by the player or the enemy.
But when I try to destroy the gameobject it shows error
“Destroying assets is not permitted to avoid data loss.”
I can solve this by adding a script directly to the prefab but I want to destroy it from the contorller script.

public class HerbController : MonoBehaviour {

public GameObject Herbs;
public Vector3 HerbsPosVals;

// Use this for initialization
void Start () {

	InvokeRepeating ("SpawnHerbs", 1, 5);
	Destroy(Herbs, 5); /// the code here is throwing error
}

void SpawnHerbs(){

	Vector3 HerbsPos = new Vector3 (Random.Range(-HerbsPosVals.x, HerbsPosVals.x), HerbsPosVals.y, Random.Range(-HerbsPosVals.z, HerbsPosVals.z));
	Instantiate (Herbs, HerbsPos, Quaternion.identity);

}

}

Please anyone with the C# solution or I am doing it wrong.

Its all messed up in your script :slight_smile:
What do you want to destroy a prefab for?? Why do you do it in Start?

And I guess you confuse what is Prefab and what is Instantiated object.

Prefab - is an Idea of object, not the object. It does not exists in scene and cant be destroyed (I’m a bit simplifies the situation, but it should be more clear). And when you instantiate an object (or objects) from prefab - you can move this object, you can interact with it, and you can destroy object.

So, you should destroy objects, not prefab.
You could store a link to each instantiated object (and destroy it from your spawner controller), or you could make a controller for your herbs and each herb will destroy itself when needed).

Don’t destroy in Start.

Get a reference to the instantiated object and use that reference to destroy it. Instantiate does return an Object type, i’m casting it to ensure i don’t have to worry about answering questions about the difference between a Unity Object type and .net’s Object type.

public class HerbController : MonoBehaviour {
public GameObject Herbs;
public Vector3 HerbsPosVals;

	// Use this for initialization
	void Start () {
		InvokeRepeating ("SpawnHerbs", 1, 5);
	}

	void SpawnHerbs(){
		Vector3 HerbsPos = new Vector3 (Random.Range(-HerbsPosVals.x, HerbsPosVals.x), HerbsPosVals.y, Random.Range(-HerbsPosVals.z, HerbsPosVals.z));
		GameObject go = (GameObject)Instantiate (Herbs, HerbsPos, Quaternion.identity);
		Destroy(go, 5); // destroy after 5 seconds
	}
}