- Home /
The question is answered, right answer was accepted
Strange code Debugging
Hi everyone! I'am just trying to move some children to an other gameObject, but only half was been transfered correctly!?
Here my code:
print("old Child Count " + oldGameObject.transform.childCount); int i = 0; foreach(Transform child in oldGameObject.transform) { print("Moving child '" + i + "' to new"); child.parent = newGameObject.transform; i++; }and here the result:
old Child Count 6 Moving child '0' to new Moving child '1' to new Moving child '2' to newAnd that all...
Somebody can explain that?
Answer by meat5000 · Feb 19, 2015 at 02:45 AM
The method you used simply iterates from bottom to top. As you move the objects the count reduces and so as the index increases objects get missed out.
My method iterates from top to bottom using GetChild(index). (Explain how this for loop works with cnt>=0 ??)
using UnityEngine;
using System.Collections;
public class CHILDMOVE : MonoBehaviour {
public GameObject oldGameObject;
public GameObject newGameObject;
void Start () {
oldGameObject = gameObject;
NewFunc ();
}
void NewFunc () {
print("old Child Count " + oldGameObject.transform.childCount);
int blah = oldGameObject.transform.childCount;
for(int cnt=blah-1; cnt>=0; cnt--)
{
print("LATEST old Child Count " + oldGameObject.transform.childCount + " " + cnt);
oldGameObject.transform.GetChild(cnt).parent = newGameObject.transform;
}
}
}
So easy... Thank's you very much! Why native foreach iterates from bottom to top ins$$anonymous$$d of top to bottom? I don't care anymore... but, I'm curious?
"Bottom to top" = "From [0] to [n]" = That's how all default iterators work in every program$$anonymous$$g language - from the first to the last element.
Follow this Question
Related Questions
Kinematic Child Object Jumping Above Player 1 Answer
Pressing E three times in order for it to work. 1 Answer
Count how many parents in Hierarchy? 2 Answers
how do i tell how many childs a object has 3 Answers
Transform child out of bounds 1 Answer