在 Unity 中销毁实例化对象

Destroying instantiated objects in Unity

我想在 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),但只有最后一个按钮被销毁。可能的解决方案是什么?谢谢

当您调用 Destroy(goButton) 时,它只会销毁该变量正在引用的当前 GameObject(而不是它曾经引用的所有 GameObject)。看起来您要解决的问题是 "How can I destroy multiple instantiated objects" 并且您在这里有两个基本选项。一种是在 C# 集合中保存对所有 GameObjects 的引用(如 List<>HashSet<>)。您的另一种选择是使用一个空的 GameObject 作为 "container object",父项下的所有内容,然后在完成所有操作后销毁容器。

Creating/Deleting 通过第一个选项看起来像这样:

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