Infinite Loop? when Setting Parent

I’m running into an issue that I can’t seem to figure out, though I’m sure it’s probably something simple. Setup is an attempt to make a modal dialog box. I had a yes/no working, and I’ve duplicated that and started working on one that allows you to choose something. There is a panel (dialogObject in code below) that covers all UI, a child panel that takes up about 80% of the visible space (the actual dialog), and a grandchild panel (cardSpread below) containing a gridbaglayout inside that.

The goal of this code is to remove what was in the previous iteration of this dialog (it’s a static), and replace it with new collection. Everything works, up until I try to set the parent of the newly created object to the panel with the gridbaglayout. At that point, it seems to enter a infinite loop; memory usage skyrockets to about 98% of my cpu, unity freezes, and I have to use Task Manager to kill it.

So, I guess the question is – what am I doing wrong? This doesn’t look like it’s any different than things I’ve done before.

    Transform cardSpread = dialogObject.transform.Find ("Panel/CardSpread");
	// Delete all old children
	while (cardSpread.transform.childCount > 0)
	{
		GameObject.Destroy (cardSpread.GetChild (0).gameObject);
	}

	// Add new children
	foreach (CardData data in cardReference)
	{

		Debug.Log ("Told to show card " + data.cardName);
		GameObject go = GameObject.Instantiate (cardPrefab);
		CardController cc = go.GetComponent<CardController> ();
		cc.CardInfo = data;

		if (go.transform == null)
			Debug.Log ("Transform is null");  // Does not get triggered.
		if (go.transform.parent == null)
			Debug.Log ("Parent is null");  // Does get triggered.
		//Debug.Log (go.transform.parent.name);
		Debug.Log (cardSpread.name);  // Properly shows "CardSpread"

		go.transform.SetParent (cardSpread); // This line causes issue
		Debug.Log ("Card should now be shown");

	}

1 Answer

1

It would help to know what CardData looks like but I would start by making these changes

Transform cardSpread = dialogObject.transform.Find ("Panel/CardSpread");

// Delete all old children
for (int i = 0; i < cardSpread.childCount; i++)
{
    if (cardSpread*.childCount > 0)*

{
GameObject.Destroy (cardSpread*.GetChild(0).gameObject);*
}
}

if (cardPrefab != null)
{
// Add new children
foreach (CardData data in cardReference) // here is the main problem
{
Debug.Log ("Told to show card " + data.cardName);
GameObject go = GameObject.Instantiate (cardPrefab);

if (go != null)
{
CardController cc = go.GetComponent ();
if (cc != null)
{
cc.CardInfo = data;

if (go.transform.parent == null)
Debug.Log (“Parent is null”); // Does get triggered.

//Debug.Log (go.transform.parent.name);
Debug.Log (cardSpread.name); // Properly shows “CardSpread”

go.transform.SetParent(cardSpread, false); // This line causes issue
Debug.Log (“Card should now be shown”);
}
else
{
Debug.Log (“Transform is null”); // Does not get triggered.
}
}
}
}