I want to delete an instantiated gameobject in Unity. I am using a for loop in instantiating a dynamic buttons and I want to destroy it before using it again because number of buttons is just appending and not over writing. This is my code in instantiating:
for(int i = 0; i < num; i++)
{
goButton = (GameObject)Instantiate(prefabButton);
goButton.transform.SetParent(panel, false);
goButton.transform.localScale = new Vector3(1, 1, 1);
//print name in Button
goButton.GetComponentInChildren<Text> ().text = names[i];
//get Url from firebase
string Url = url[i];
WWW www = new WWW (Url);
yield return www;
Texture2D texture = www.texture;
//load image in button
Image img = goButton.GetComponent<Image>();
img.sprite = Sprite.Create (texture, new Rect (0, 0, texture.width, texture.height),Vector2.zero);
Button tempButton = goButton.GetComponent<Button>();
int tempInt = i;
string name = names [i];
tempButton.onClick.AddListener (() => hello (tempInt, name));
}
I tried adding Destroy(goButton) before the for loop but only the last button is being destroyed. What could be the possible solution? Thanks
When you call Destroy(goButton)
, it will only destroy the current GameObject
that variable is referencing (not all the GameObject
s it used to reference). It seems like the problem you're trying to solve is "How can I destroy multiple instantiated objects" and you have two basic options here. One would be to save references to all the GameObjects
in a C# collection (like a List<>
or HashSet<>
). Your other option would be to use an empty GameObject
as a "container object", parent everything under that, then destroy the container when you're done with them all.
Creating/Deleting via the first option would look something like this:
// Note this class is incomplete but should serve as an example
public class ButtonManager
{
private List<GameObject> m_allButtons = new List<GameObject>();
public void CreateButtons()
{
for (int i = 0; i < num; i++)
{
GameObject goButton = (GameObject)Instantiate(prefabButton);
m_allButtons.Add(goButton);
...
}
}
public void DestroyButtons()
{
foreach (GameObject button in allButtons)
{
Destroy(button);
}
allButtons.Clear();
}
}