Destroying created game objects from a prefabs.
Hi, I have a small problem. I have script which is creating Game Objects based on created Prefab and setting it under a parent.
I need to make a method to destroy all created GameObject and "restart" a Prefab, kind off.
public class MakingButton : MonoBehaviour {
public GameObject prefabButton;
public RectTransform ParentPanel;
// Use this for initialization
public void NewButton ()
{
GameObject goButton = (GameObject)Instantiate(prefabButton);
goButton.transform.SetParent(ParentPanel, false);
goButton.transform.localScale = new Vector3(1, 1, 1);
}
I was trying to use few examples but I could not fix that, maybe you will help me...
Thank you in advance. :)
Answer by tormentoarmagedoom · Jun 19, 2018 at 08:54 PM
Good day.
Once an object is intantiated via code, are not different from the others, so there is no a function to detect them.
But you can do things, like, every time you instantiate something, change its tag and then after unse GameObject.FindObjectsWithTag()
Or You can make them all child of some object to easy find them.
Bye! :D
Answer by Samzgadnij · Jun 21, 2018 at 05:13 PM
WoW.... So simple, so logical but still I did not figure that.
Hah.
Thank you very much!
I will try it and give an info!
#edit
I was trying to do as you wrote, it works but after mouse click (I attached this to a script) it destroys only 1, the oldest, prefab clone.
I looked for some help at forum and I merged your idea with what I have found. It creates a list and destroys all created prefabs, maybe it will help someone :)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class MakingButton : MonoBehaviour {
public GameObject prefabButton;
public RectTransform ParentPanel;
public GameObject[] prefabButtonList;
// Use this for initialization
public void NewButton ()
{
GameObject goButton = (GameObject)Instantiate(prefabButton);
goButton.transform.SetParent(ParentPanel, false);
goButton.transform.localScale = new Vector3(1, 1, 1);
}
public void DestroyButton ()
{
prefabButtonList = GameObject.FindGameObjectsWithTag ("CreatedButton");
for(var i = 0 ; i < prefabButtonList.Length ; i ++)
{
Destroy(prefabButtonList[i]);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612165100im_/https://answers.unity.com/themes/thub/images/avi.jpg)