Removing clones instantiated from prefab

Hi,
I am trying to make a function that will destroy all prefab clones when i press one button.
Here is code but when I try to run it, Unity crashes…I tried different things but it just don’t work. Hope that someone will help.

 private void ClearScreen()
    {
        if (GameManager.instance.shouldCloneBeDestroyed == true)
        {
            while (GameObject.Find("food(Clone)") != null)
            {
                Destroy(foodClone);
            }
        }
    }
    private IEnumerator Spawner()
    {
        gameObject.SetActive(true);
        yield return new WaitForSeconds(startWait);
        while (!stop)
        {
            randFood = Random.Range(0, 7);
            Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), 1, Random.Range(-spawnValues.z, spawnValues.z));
            foodClone = Instantiate(food[randFood], spawnPosition + transform.TransformPoint(0, 0, 0), gameObject.transform.rotation);
            foodClone.transform.parent = transform; 
            Rigidbody2D rigidBody = foodClone.GetComponent<Rigidbody2D>();
            spawned++;
            yield return new WaitForSeconds(timer);
        }
    }

Do you ever set stop to true on the Spawner Coroutine? If not, the problem is there and the endless loop crashes unity.

Also, doing Destroy(foodClone) seems wrong to me since you are not actually assigning what you found using GameObject.Find(“food(Clone)”) to anything after you find it… Making the foodClone variable not what you are expecting. Try (not tested):

private void ClearScreen()
{
    if (GameManager.instance.shouldCloneBeDestroyed)
    {
        foodClone = GameObject.Find("food(Clone)");
        
        while(foodClone != null) 
        {
            Destroy(foodClone);
            foodClone = GameObject.Find("food(Clone)");
        }
    }
}

It would be more performance-effective creating a tag “FoodClone”. Say, when you instance your prefab, you can use:

foodClone.tag = "FoodClone"

Searching by tags takes less resources than searching by name, and you can easily put them into an array. Then to delete them you use:

GameObject[] foodClones = GameObject.FindGameObjectsWithTag("FoodClone"); 
    foreach(GameObject foodClone in foodClones)
       GameObject.Destroy(foodClone);

if the foreach trhows any problem you can use a while loop instead:

while (foodClones.Length >0)
{GameObject.Destroy(foodClones[0]);}