销毁Unity中的实例化对象

时间:2017-03-24 14:11:42

标签: android unity3d destroy gameobject

我想在Unity中删除一个实例化的游戏对象。我正在使用for循环来实例化动态按钮,我想在再次使用它之前销毁它,因为按钮的数量只是附加而不是写入。这是我实例化的代码:

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));
    }

我尝试在for循环之前添加Destroy(goButton),但只有最后一个按钮被销毁。可能的解决方案是什么?感谢

1 个答案:

答案 0 :(得分:2)

当您致电Destroy(goButton)时,它只会销毁该变量所引用的当前GameObject(而不是它用于引用的所有GameObject)。您似乎要解决的问题似乎是&#34;我如何销毁多个实例化对象&#34;你有两个基本选择。一种方法是保存对C#集合中所有GameObjects的引用(如List<>HashSet<>)。您的另一个选择是使用空的GameObject作为&#34;容器对象&#34;,将其下的所有内容置于其下,然后在您完成所有操作时销毁容器。

通过第一个选项创建/删除看起来像这样:

// 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();
    }
}