首页 > 解决方案 > 如何销毁引用数组的对象而不将它们从 Unity 2D 中的数组中删除?

问题描述

我最近开始创建游戏,但是当我尝试破坏场景中的对象时,它们也会从列表中删除。这是代码:

        List<GameObject> objects = new List<GameObject>();
        int x = 650;
        // Here I try to destroy objects
        foreach(Transform obj in transform) {
            Destroy(obj.gameObject);
        }
        // Here I instantiate all objects from the array
        for(int i = 0;i < objects.Count;i++) {
            if(objects.Count == 3) {
                GameObject prefab_copy = (GameObject)Instantiate(objects[i], new Vector2(x, 1150), Quaternion.identity );
                prefab_copy.GetComponent<Image>().enabled = true;
                prefab_copy.transform.SetParent(parentobj.transform);
                x = x + 100;
            }
        }
        cleanItemList = true;

标签: c#unity3d

解决方案


将空值保存在列表中然后尝试从中进行实例化是危险的,请在销毁游戏对象后立即从列表中删除,您不能在播放模式下保留对已删除游戏对象的引用。

我的建可以理解你需要学习OBJECT POOLING的问题。它将帮助你重用相同的对象并提高性能。


推荐阅读