- Home /
How to get all objects instantiated from a single prefab?
I want to use GameObject.FindGameObjects that have been instantiated in my scene from a single prefab.
I am using a button to generate cubes, and I want to be able to always have all those cubes do something.... Like if I have cubes and spheres and cylinders in the scene I want to be able to make all of them separate colors so that I can differentiate between them. How do I grab all of the game objects from only one prefab in a script?
Answer by BradyIrv · Jun 12, 2019 at 08:05 PM
There's more than one way, here's two:
// add a tag to the cube prefab you are spawning in the scene
GameObject[] cubes = GameObject.FindGameObjectsWithTag("tagToSearchFor");
// add the cube to a list when you instantiate it
List<GameObject> cubes = new List<GameObject>();
GameObject cube = Instantiate(cubePrefab, position, rotation);
cubes.Add(cube);
I am also wondering how to delete these items from the list and to also delete these items from the game scene. I have buttons that generate these objects, then I want a button to clear these objects from the scene. I am going to have many buttons to generate many different kinds of objects and I also want buttons to delete only these kinds of objects.
I have tried to use the list method and I have spent days trying to get it to actually remove those instantiated objects from the scene. I have tried foreach (var obj in cubes) { Destroy(obj); } Any variations I take of Destroy(obj) does not seem to work, and I'm very desperate for the list method to work. I have the tags method working to clear all objects but I want to be able to put multiple tags on one object, which I cannot do... I want to be able to have objects in different lists. For example if I want to highlight only cubes attached to a specific surface, I could do that with the list method. (This will become an extensive program at some point)...