Hello!
I have encountered the following problem:
Two GameObjects (one empty GameObject, named “test”, and one instance of a Cube, named “Cube(Clone)”) are parented via a click of a button through the following function:
public void Child () {
foreach (Transform child in GameObject.Find("test").transform) {
GameObject.Destroy(child.gameObject);
}
Instantiate(GameObject.Find("Cube"));
GameObject.Find("Cube(Clone)").transform.parent = GameObject.Find("test").transform;
}
Unfortunately, the parenting happens every even try (1, 3, 5, …). On the uneven tries the instantiated cube is not parented.
What is wrong with the above code?
I have tried to wait for a frame, but the errouneous bahavior does not change.
I do not know why, but when i used a variable to hold the instantiated GameObject, everything works fine.
The following code works without a problem:
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
private GameObject temp;
public void Child () {
foreach (Transform child in GameObject.Find("test").transform) {
GameObject.Destroy(child.gameObject);
}
temp = Instantiate(GameObject.Find("Cube"));
temp.transform.parent = GameObject.Find("test").transform;
}
}
er, ok… why are you using Find at all in these?
Because in my original project i was creating the GameObjects in runtime. And i have a small hierarchy, in which to search for them. Additionally, that was the smallest sample of the problem that came to my mind, when i posted here. Mind you, that small source code represents the problem very well.