【问题标题】:Destroying instantiated objects in Unity在 Unity 中销毁实例化对象
【发布时间】:2017-03-24 14:11:42
【问题描述】:

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

【问题讨论】:

    标签: android unity3d destroy gameobject


    【解决方案1】:

    当您调用Destroy(goButton) 时,它只会破坏该变量正在引用的当前GameObject(不是它曾经引用的所有GameObjects)。您要解决的问题似乎是“我如何销毁 多个 实例化对象”,您在这里有两个基本选项。一种方法是在 C# 集合中保存对所有 GameObjects 的引用(如 List&lt;&gt;HashSet&lt;&gt;)。您的另一个选择是使用空的GameObject 作为“容器对象”,将其下的所有内容作为父对象,然后在完成所有操作后销毁容器。

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

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

    【讨论】:

    • 谢谢你uuuuuuuu
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多