Destroy The Same Objects Before Instantiating

Hello Guys, I have this kind of situation now.

[29231-безымянный.png|29231]

I am instantiating some objects

public void CreateItems(float i, int numberOfObjects, float iterator, float offsetX, float yPosition, GameObject itemPrefab)
	{
		for(i = iterator; i <= numberOfObjects - 1; i += offsetX)
		{
			GameObject clone = Instantiate (itemPrefab, new Vector2 (i , yPosition), Quaternion.identity) as GameObject;
			prefabs.Add(itemPrefab);
		}
	}

I’am adding them to a list.

Now Im doing a button

if(GUI.Button(new Rect(20,40,80,20), "CreateandDelete"))
		{
			
			autoObject.CreateItems(autoObject.i, autoObject.numberOfObjects, autoObject.iterator, autoObject.offsetX,autoObject.yPosition,autoObject.itemPrefab);
			
		}

Now I want to delete Them and instantiate again when im pressing a button.

As I said I stored all of them in a list. And I have to go trough all of them

public void DeleteClones(GameObject itemPrefab)
	{
		foreach(GameObject i in prefabs)
		{
			Destroy(itemPrefab);
		}
	}

But I kinda suck at this step, any help here?

On line 6 of your CreateItems method your should add the clone to the list, not the prefab.

prefabs.Add(clone);

[Closed]. Answer

public void DeleteItems()
	{
		for(int i = 0 ; i < prefabs.Count; i ++)
		{
			Destroy(prefabs*.gameObject);*
  •  }*
    
  • }*
    or going trough an foreach loop.
    foreach (GameObject i in prefabs)
  •  				Destroy (i);*