- Home /
Apply changes to a random child from sublist
Hi, ALL!!!
I have a script that generates 8 objects (prefabs) and place them in 8 (of 12) random slots in the scene, in the way that the objects become the children of the slots. Further I need to apply changes to the children objects, but choosing randomly 1 object from the list of objects that are placed along a certain wall. I have a script to make it. But I don't know why, instead of just 1 object that has to change, all the objects along the wall perform changes. Does someone have any idea where is a mistake here???
Thank you!
Code:
GameObject[] children = new GameObject[Wall1.Length];
int count = 0;
foreach (GameObject childSlot in Wall1) {
if (childSlot.transform.childCount > 0) {
Transform t = childSlot.GetComponentsInChildren<Transform> () [1];
children [count] = t.gameObject;
count++;
int changeFunction = UnityEngine.Random.Range (1, 7);
int randomObjectIndex = UnityEngine.Random.Range (0, count - 1);
Changes (changeFunction, children [randomObjectIndex]);
}
}
Answer by Norax · Jul 07, 2014 at 03:00 PM
With the foreach you move across all the items in the wall. Under that loop, you apply once a random change, and that random change is applied as many times as items you have in the wall.
Solution? Move this lines outside the foreach:
int changeFunction = UnityEngine.Random.Range (1, 7);
int randomObjectIndex = UnityEngine.Random.Range (0, count - 1);
Changes (changeFunction, children [randomObjectIndex]);
Thanx, but it does not help. When I move it outside, the code does not run as it is unable to find count and children. If I move just one parenthesis, it applies changes to all of the objects as before. $$anonymous$$ore ideas?
@Norax's suggestion should work. You need to move lines 11 - 13 below line 15. These lines will still exist in the same function, so count and children will exist.