2

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

Dave
  • 171
  • 2
  • 11
  • How are you creating the buttons and text, are you using OnGui or are you using Gui objects dragged in to the scene view? – Scott Chamberlain Jun 29 '16 at 15:52
  • it's utterly impossible to help unless you *include your code*. note that if you are using the ancient "onGui" system, ***you cannot do that***. it is deprecated and no longer works. – Fattie Jun 29 '16 at 15:56
  • I am using new GUI system. I have Canvas with ScrollView. The Texts and Buttons are created using Instantiate. I have no idea how to identify the buttons for ex. second button == second item. – Dave Jun 29 '16 at 16:05
  • Destroy(yourGameobject) – johnny 5 Jun 29 '16 at 16:26

1 Answers1

3

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
        }
Jerry Switalski
  • 2,690
  • 1
  • 18
  • 36