Search code examples
c#unity-game-engineunity3d-gui

Unity3D list made of scrollview and buttons - how to delete item?


I have made list in Unity3D with ScrollView, Texts and Buttons. When user clicks button near the item - the item should be deleted. Buttons and Texts are created with Instantiate method. The list of items is generic list (List).

List of items:

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

Creating buttons and texts:

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

How to detect which item's button is clicked to remove the item?

I have no idea how to get that second button click == second item delete.

List made with ScrollView, Texts and Buttons


Solution

  • Just add one line of code:

            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
            }