Help. In the code below, I have a gameobject which simply holds a series of buttons. When I switch nodes (calling SetNode()) I want to clear out that gameobject and create a series of new buttons. However, when I do this, the buttons are instantiated, but all scripts on it are disabled. If I manually reenable them, they appear normally and in their expected location, but the OnClick Listener for the button is revealed to be improperly set. I have verified that the prefab definition does not have these scripts disabled.
However, this behavior does not occur when I comment out the Destroy(child.gameObject) line (Line 11) - the buttons are created normally and their OnClick handlers work properly.
So my question is - Why does destroying the existing game objects (button prefabs) affect the subsequently instanced versions? Is there a better way to destroy all prefab children?
Thanks for your help!
public void SetNode(Node node)
{
currentNode = node;
nodeName.text = "[" + node.nodeLevel + "] " + node.NodeName;
// Create Travel Buttons to Other Nodes
// Remove all existing buttons
foreach (Transform child in travelPanel.transform)
{
Destroy(child.gameObject); /* This is the line that apparently causes the problem */
}
// Create new buttons
foreach (Node destination in node.neighbors.Keys)
{
Debug.Log("Creating Travel Button");
GameObject travelButton = Instantiate(travelButtonPrefab, travelPanel.transform);
travelButton.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => FindObjectOfType<Character>().Move(destination));
travelButton.GetComponentInChildren<TMPro.TextMeshProUGUI>().text = destination.NodeName + " [" + node.neighbors[destination] + "]";
}
}