- Home /
Why is the wrong child activated, although I have the right index?
Hello everybody,
I have Instantiated a list of Prefabs, with several Gameobjects as Children, in the Awake part and deactivated them. I want to randomly activate them during the game phase.
It actually works but the wrong GameObject is activated.
Part of my Code is this:
for (int i=0; i<2; i++) {
randColor = Random.Range (0, numColors);
gameStats.correctColor.Add (randColor);
randShape=Random.Range(0,2);
randTexture=Random.Range(3,6);
if(i==0) {
indicator[i].transform.GetChild(randShape).gameObject.SetActive(true);
gameStats.correctTexture.Add (randShape);
indicator[i].transform.GetChild(randShape).renderer.material.color = gameStats.myColors [randColor];
}else{
indicator[i].transform.GetChild(randTexture).gameObject.SetActive(true);
gameStats.correctTexture.Add (randTexture);
indicator[i].transform.GetChild(randTexture).renderer.material.color = gameStats.myColors [randColor];
}
}
I use "randShape" and "randTexture" as the first should only get a random number of the 3 Child GameObjects and the rest a random number of the last 4.
However I have added some debug code and I get the following code in the console and the result in the manager:
As You can see for the first prefab index is 0 and randShape is 0 and the first Child Object in the Hierarchy is activated. So everything as it should be.
BUT for prefab index 1 and randShape = 4 the 2nd Child Object is activated instead the 5th one.
Anybody an idea why?
Thanks for the help?
-Gerd
Answer by ArkaneX · Mar 19, 2014 at 04:14 PM
You can't rely on an order of children in hierarchy window. They are sorted by name, and their order might be different than the order of internal objects collection.
To achieve the desired result, you either have to keep children info in some additional list, which is properly sorted, or you can retrieve all children, sort them by name and select correct one. I guess you will be calling this code from time to time only, so second solution should be ok.
Found this out by accident, the "official" child order, that the code uses, is the order they were added as children. So, to make "order you see" the same as "order computer sees," remove all children (I drag them into an empty, to keep them together) and re-add them in order.
Agree, though one has to remember to repeat the operation after another child is added, which might break the order again.