在Unity3D编辑器中添加GameObject时,Unity会自动按照GameObject的名称进行排序(暂未找到设置该排序开关的功能,如有还请网友告知~)。当使用Transform.GetChild(index)遍历某GameObject的子节点时,其索引顺序也是根据该排序而定。
除了在编辑器中添加GameObject以外,还可以在代码中动态创建GameObject并添加到当前场景中,例如:
codeA: son_transform.parent = father_transfrom; son_transform.name = "object_name";
codeB : son_transform.name = "object_name"; son_transform.parent = father_transform;
codeA与codeB的差别在于两个语句的先后顺序,但在使用GameObject.GetChild()来遍历子节点时,这一先后顺序会对子节点遍历顺序产生影响。
mother_object.name = "C"; for (int i = 0; i < 3; i++ ) { GameObject new_obj = GameObject.Instantiate(mother_object) as GameObject; new_obj.transform.parent = transform; new_obj.name = "T" + i; } for (int i = 0; i < 3; i++) { GameObject new_obj = GameObject.Instantiate( mother_object ) as GameObject; new_obj.transform.parent = transform; new_obj.name = "A" + i; } for (int i = 0; i < 3; i++) { GameObject new_obj = GameObject.Instantiate( mother_object ) as GameObject; new_obj.transform.parent = transform; new_obj.name = "F" + i; } for (int i = 0; i < transform.childCount;i++ ) { Debug.Log("transform " + i + " name " + transform.GetChild(i).name); }
上面的测试代码段使用的是codeA方式来添加子节点,相应的输出结果是:
transform 0 name A0transform 1 name A1
transform 2 name A2
transform 3 name F2
transform 4 name F1
transform 5 name F0
transform 6 name T2
transform 7 name T1
transform 8 name T0
而如果将上面的测试代码改成使用codeB方式来添加子节点,其输出结果则是:
transform 0 name A0
transform 1 name A1
transform 2 name A2
transform 3 name F0
transform 4 name F1
transform 5 name F2
transform 6 name T0
transform 7 name T1
transform 8 name T2
由此推断,在执行transform.parent = parent_trans;会触发由小到大的插入排序,而重命名时不会再次排序。
所以在代码中动态添加GameObject,并且代码逻辑依赖于子节点的遍历顺序时,要格外注意".parent =" 和 ".name ="的执行顺序。