由滚动视图和按钮组成的Unity3D列表 - 如何删除项目?

时间:2016-06-29 15:37:29

标签: c# unity3d unity5 unity3d-gui

我在Unity3D中使用ScrollView,Texts和Buttons制作了列表。 当用户单击项目附近的按钮时 - 应删除该项目。 使用Instantiate方法创建按钮和文本。 项目列表是通用列表(列表)。

项目清单:

public List<Item> Items { get; set; }

创建按钮和文字:

public Button itemButton;
public Text itemText;
(...)
public void ShowItems()
{
    ClearItems(); //Destroys button and text gameObjects.

    foreach (var item in Globals.Items)
    {
        var text = Instantiate(itemText) as Text;
        var button = Instantiate(itemButton) as Button;
        button.GetComponentInChildren<Text>().text = "Delete";
        textsList.Add(text); //save Text element to list to have possibility of destroying Text gameObjects
        buttonsList.Add(button);//save Button element to list to have possibility of destroying Button gameObjects
        text.gameObject.SetActive(true);
        button.gameObject.SetActive(true);
        //(...) Setting GUI items position here
    }
}

如何检测单击哪个项目的按钮以删除该项目?

我不知道如何获得第二个按钮==第二个项目删除。

List made with ScrollView, Texts and Buttons

1 个答案:

答案 0 :(得分:3)

只需添加一行代码:

        foreach (var item in Globals.Items)
        {
            var text = Instantiate(itemText) as Text;
            var button = Instantiate(itemButton) as Button;
            button.GetComponentInChildren<Text>().text = "Delete";
            textsList.Add(text); //save Text element to list to have possibility of destroying Text gameObjects
            buttonsList.Add(button);//save Button element to list to have possibility of destroying Button gameObjects
            text.gameObject.SetActive(true);
            button.gameObject.SetActive(true);

            // this line:
            button.onClick.AddListener(delegate {Destroy(text.gameObject); Destroy(button.gameObject);});

            //(...) Setting GUI items position here
        }