Mechanic
Mechanic

Reputation: 3

How to destroy dynamic elements from panel in unity c# script

Trying to delete the items from the panel (empty it) and then repopulate the panel with new items (buttons)

I've already tried to delete each element with the foreach you see below with no luck

public GameObject Button;
public Transform buttonContainer;
public void create_buttons(Orbital o)
{
    GameObject go = Instantiate(Button);
    var panel = GameObject.Find("station_panel");
    //Destroy(GameObject.Find("station_panel"));

    foreach (UnityEngine.UI.Button b in panel.GetComponents<UnityEngine.UI.Button>())
    {
        //Destroy(b.gameObject);
        b.enabled = false;
    }

    go.transform.position = panel.transform.position;
    go.GetComponent<RectTransform>().SetParent(panel.transform);
    //go.GetComponent<RectTransform>().SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, 10);

    go.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => onClick());
    go.GetComponentInChildren<Text>().text = o.name;
}
void onClick()
{
    Debug.Log("aaaaaaaaaaaaaaa");


    canvas.enabled = false;
}

Upvotes: 0

Views: 3677

Answers (3)

qq98360
qq98360

Reputation: 11

DestroyImmediate(i-am-gameobject);

Upvotes: 1

The panel's transform hierarchy contains a reference to them.

Transform panelTransform = GameObject.Find("station_panel").transform;
foreach(Transform child in panelTransform) {
    Destroy(child.gameObject);
}

Upvotes: 2

VectorX
VectorX

Reputation: 667

Make a List and add any button you create for your panel.

Once you want to clear it, clear this list, but GetCompoenents will not return all the buttons in your Panel gameobject as you cant add 2 button component to a single gameobject.

Also add -using UnityEngine.UI- to the top of your script to be easily read for to be like

 foreach (Button b in list)
{
    Destroy(b.gameObject);        
}

Upvotes: 1

Related Questions