【问题标题】:How to destroy the first clone of a UI Image using an array every time I press a button in Unity?每次在 Unity 中按下按钮时,如何使用数组销毁 UI 图像的第一个克隆?
【发布时间】:2018-01-26 18:00:45
【问题描述】:

这是我在 void Update() 函数中使用的一行代码,用于克隆 UI 图像 car

Image c = Instantiate (car, carPos, transform.rotation, transform.parent) as Image;

如何在每次按下按钮时将所有克隆存储到一个数组并销毁第一个?

如果我使用Destroy(c);,那么只有在那个时刻实例化的克隆会被销毁。但我只希望第一个克隆被销毁(每次按下按钮)。

【问题讨论】:

  • 使用List<T>?
  • @Draco18s 能否提供代码?
  • SO 不是代码编写服务,这是一个问答网站。
  • @Draco18s 好吧,人们确实通过提供 2 或 3 行代码(如果可以的话)来帮助其他人,这可能会帮助提出问题的人。感谢您的帮助。

标签: c# unity3d


【解决方案1】:

您可能希望将图像存储在 FIFO 类型的集合中,例如 Queue<GameObject>。然后,您可以像这样将项目添加到队列中:

queue.Enqueue(c.gameObject);

然后像这样销毁对象:

GameObject.Destroy(queue.Dequeue());

因此,如果用于销毁图像的按钮在您的代码中命名为button,您的代码将如下所示:

Button button;
Queue<GameObject> queue;

public void Start() {
    Image c = Instantiate (car, carPos, transform.rotation, transform.parent) as Image;
    queue.Enqueue(c.gameObject);
    //Populate the list using the code above.
    button.onClick.AddListener(() => 
        if(queue.Count > 0) { GameObject.Destroy(queue.Dequeue()); }
    });
}
    //This will remove an image from the list and destroy it when the button is clicked.

希望这会有所帮助!

【讨论】:

  • 谢谢哥们。这种技术会帮助我。但不知何故,克隆并没有被摧毁。是不是因为clone是UI Image和GameObject.Destroy(queue.Dequeue());仅适用于 GameObjects?
猜你喜欢
  • 2021-11-24
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 2013-08-08
  • 1970-01-01
相关资源
最近更新 更多