简体   繁体   中英

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

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

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

DestroyImmediate(i-am-gameobject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM