[C#] How can I destroy instantiated prefabs when many are created with the same name?

Hi everyone,

I’m trying to make a plant that grows in 4 stages, each stage is a prefab, my script is attached to an empty GameObject, everything is working just fine in my scene except when I want to use this GameObject multiple times at once, because then more than one instance of this script is running and they interfere with each other and causing unwanted results, I was wondering how can I have unique names for every prefab instantiated by the script?

thank you for the help, here is my script if you want to have a look.

using UnityEngine;
using System.Collections;

public class PlantCycle : MonoBehaviour 

{
	
	public float plantGrowth = 1;
	public float plantSize;
	public bool plantStage01 = true;
	public bool plantStage02 = false;
	public bool plantStage03 = false;
	public bool plantStage04 = false;
	

	void Start () 

	{

		Instantiate (Resources.Load ("Prefabs/Prefab_PlantStage01"), this.transform.position, this.transform.rotation); //Initialate Plant Phase 1

	}



	void Update () 
	
	{


		
		plantSize = plantSize + plantGrowth * Time.deltaTime;


		if (plantSize >= 10 && plantStage02 == false) 

		{
			Instantiate (Resources.Load ("Prefabs/Prefab_PlantStage02"), this.transform.position, this.transform.rotation);

			plantStage02 = true;

			Destroy (GameObject.Find("Prefab_PlantStage01(Clone)"));

		}



		else if (plantSize >= 20 && plantStage03 == false) 

		{
			Instantiate (Resources.Load ("Prefabs/Prefab_PlantStage03"), this.transform.position, this.transform.rotation);
			
			plantStage03 = true;

			Destroy (GameObject.Find("Prefab_PlantStage02(Clone)"));		
		}



		else if (plantSize >= 30 && plantStage04 == false) 

		{
			Instantiate (Resources.Load ("Prefabs/Prefab_PlantStage04"), this.transform.position, this.transform.rotation);
			
			plantStage04 = true;

			Destroy (GameObject.Find("Prefab_PlantStage03(Clone)"));


		}
	}
}

try making your bool variables private, not public

:slight_smile:

In general, you never need to search by name. If you create something, you just remember what it is, in a variable. Then, later, you can do stuff to it using that variable.

Take a look at the example pages for Instantiate. The general idea is GameObject p1=Instantiate(plant1preFab); then anytime later, talk to “your” plant1 with things like p1.position=. As a bonus, it also runs faster (not that speed matters in 99% of your code.)