2

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

物品清单:

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
    }
}

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

我不知道如何让第二个按钮单击 == 第二个项目删除。

使用 ScrollView、文本和按钮制作的列表

4

1 回答 1

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
        }
于 2016-06-29T16:27:18.350 回答