Destroying all GameObjects with a button

Hello,
Is there a straight forward way to have a button Destroy() all instantiated game objects?

I have a List myList holding all GameObjects created.

I created a Button and a Script but I cant figure out how to pass in myList to it as a ref.
All the tutorials for buttons I’m finding are to just have it print out a debug. The most comprehensive button tutorial I went through had the button change scenes. I found another tutorial how to make a button destroy() a specific game object. Thats all great. But what I need does not translate to what I learned so far about buttons.

Im probably doing this all wrong.

So instead of pasting code, maybe I’ll stick to the goal…

How do I Destroy(allinstantiatedgameobjects) with a button click?

My program instantiates GameObjects randomly during play, so they aren’t things I can just click on in development and specify I want destroyed. I am basically looking for a reset button.

Just iterate through the list, destroy the objects, and clear the list. What have you tried so far?

I can only do that (I as in what I know how to do) in my game controller script.

Here is what I tried. I created a button called ResetButton.
I then created a script for the button called ResetButtonTap.
Here is ResetButtonTap.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ResetButtonTap : MonoBehaviour
{
    public void ResetButtonTapped(ref List<GameObject> objList)
    {
        foreach (GameObject spot in objList)
        {
            Destroy(spot);
        }
        objList.Clear();
    }
}

Thats about it. I dragged ResetButtonTap.cs into the On Click() area of the button.
I know I’m missing something here. I’m thinking I’m going about it the wrong way.

Why not reset it in the same class the list is in? You cannot pass a reference with a button unless you have the button call a method which then calls that method.

I guess I don’t know how to make the button interact with the class that the list is in.

Just create a public method in that class, and in the inspector for the button you add that method to the on button press event.

private List<GameObject> someListOfGameObjects = new List<GameObject>();

public void DoomsdayButtonPressed()
{
    foreach (GameObject daysAreNumbered in someListOfGameObjects)
    {
        Destroy(daysAreNumbered);
    }

    someListOfGameObjects.Clear();
}

I love your function names and object names! :smile:
Great it worked. Thank you very much.

Good luck on your pirate game. I’ll be lookin out for it. Thank you matey!

1 Like