user2326369
user2326369

Reputation:

Code not executing when condition is accomplished

I'm trying to organize some transforms in hierarchy by changing those transforms parents by code. I have this function:

private GameObject[,] SpawnCullingGroups(GameObject[,] cG)
     {
         for(int i = 0; i < cG.GetLength(0); i++)
         {
             for (int j = 0; j < cG.GetLength(1); j++)
             {
                 GameObject c = Instantiate(Culler, new Vector3(i * 32f,0,j * 32f), Quaternion.identity) as GameObject;
                 c.name = "CoullingGroup";
                 cG[i,j] = c;
                 foreach (Transform child in GameObject.Find("MapContainer").transform)
                 {
                     if (child.position.x >= c.transform.position.x && child.position.x <= (c.transform.position.x + 32)
                         && child.position.z >= c.transform.position.z && child.position.z <= c.transform.position.z + 32) {
                         child.parent = cG [i, j].transform;
                     }
                 }
             }
         }

         return cG;
     }

Sometimes the if conditions triggers and changes it parent, but with some transforms it wont work. I end up with some strange pattern: enter image description here

All that sector (10 * 10) should be green (child of the CoullingGroup in that area). Grids are perfect, meaning each block is 3.2 units length and 3.2 wide, and they are separated by 3.2 units in x and z axis.

Those who aren't child of the CullingGroup are in the range of condition. Am I missing something?

Upvotes: 0

Views: 62

Answers (1)

user2326369
user2326369

Reputation:

With the help of @andeart we solved this by changing the loop into this: foreach (Transform child in GameObject.Find("MapContainer").GetComponentsInChildren<Transform>())

We also added another piece of code to avoid MapContainer be deleted.

if (child.name == "MapContainer") {
    continue;
}

Upvotes: 2

Related Questions