Iterating through children from parent in Unity and changing their coordinates

44 Views Asked by At

Parent-child tree

I want to be able to change the coordinates of all of the individual units in a floor and deactivate some of the cubes in the units. I want to be able to access these game objects from a script that's attached to floor without hardcoding them in as: "public GameObject unit1; public GameObject unit2; public GameObject cube1; etc etc" because there will be many of them. I want to be able to iterate through them and change their coordinates and deactivate some of them in void Start(), but everything I've tried thus far has failed.

I've tried this, but couldn't change the coordinates in the ingame objects by changing them in Transform[] units in C#. I've also tried loading the children in every other way that's possible and changing their coordinates and got the same result.

Transform[] units = new Transform[floorObject.transform.childCount];

for (int i = 0; i < floorObject.transform.childCount; i++)
{
    units[i]= floorObject.transform.GetChild(i);
}
1

There are 1 best solutions below

0
alihank On

I couldn't understand your question well. As far as I understand you want to move your child objects but the code you have provide only access the childs. So here I try something else (not tested). Make sure that code is attached parent object.

public class FloorManager : MonoBehaviour
{
    void Start()
    {
        // Loop through all children
        for (int i = 0; i < transform.childCount; i++)
        {
            Transform child = transform.GetChild(i);

            // Here you can change the child position
            child.position += new Vector3(1, 0, 0); 
            
        }
    }

}