unity3d 删除预制件的克隆

iqjalb3h  于 2022-12-04  发布在  其他
关注(0)|答案(2)|浏览(483)

我正在制作一个“游戏”,在这个游戏中,一个物体被显示出来,你可以在以后创建预制件的克隆或者删除它们。

public class globalControl : MonoBehaviour
{
    public GameObject prefabInstance;
    GameObject prefabInstanceClone;

    void Update()
    {
        if(Input.GetKeyDown("c"))
        {
            prefabInstanceClone = Instantiate(prefabInstance, transform.position, Quaternion.identity) as GameObject;

        }

        if (Input.GetKeyDown("d"))
        {
                Destroy(prefabInstanceClone);
        }
    }

}

为了制作克隆体,我使用了

if(Input.GetKeyDown("c"))
   {
     prefabInstanceClone = Instantiate(prefabInstance, transform.position, Quaternion.identity) as GameObject;

    }

和删除

if (Input.GetKeyDown("d"))
    {
      Destroy(prefabInstanceClone);
    }

我没有问题克隆预制我有,但当我试图删除克隆,我只能删除最后一个创建,我需要能够删除所有的克隆我有。

pexxcrt2

pexxcrt21#

public GameObject prefabInstance;
List<Object> prefabInstanceClones = new List<Object>();

void Update()
{
    if (Input.GetKeyDown("c"))
    {
        prefabInstanceClones.Add(Instantiate(prefabInstance, transform.position, Quaternion.identity));
    }

    if (Input.GetKeyDown("d"))
    {
        var last = prefabInstanceClones.LastOrDefault();
        prefabInstanceClones.Remove(last);
        Destroy(last);
    }
}
lzfw57am

lzfw57am2#

public class globalControl : MonoBehaviour
{
    public GameObject prefabInstance;
    GameObject prefabInstanceClone;

    void Update()
    {
        if(Input.GetKeyDown("c"))
        {
            prefabInstanceClone = Instantiate(prefabInstance, transform.position, Quaternion.identity) as GameObject;
        }
        if (Input.GetKeyDown("d"))
        {
           foreach (var objects in prefabInstanceClone)
            {
            Destroy(objects );
            }
        }
    }
}

相关问题