'How to loop recursive and map first time all possible levels to recursive?
public void IterateOverChild(Transform original, int currentLevel, int maxLevel)
{
if (currentLevel > maxLevel) return;
for (var i = 0; i < original.childCount; i++)
{
Debug.Log($"{original.GetChild(i)}");
allChildren.Add(original.GetChild(i));
IterateOverChild(original.GetChild(i), currentLevel + 1, maxLevel);
}
}
Usage example
void Start()
{
IterateOverChild(transform, 0, 23);
}
but in this case i'm guessing that there are 23 levels to loop through recursive. maybe there are 60 levels or 3 levels ?
how can i make that firs time the method will loop through all sub objects and each time it's getting deeper to a new level to log for example the level number like :
Debug.Log("Level : " + levelNum);
And in the end also to use Debug.Log to display the total levels. So in the end i will know from how much levels amount i can chose to recursive.
Solution 1:[1]
You can use something like this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Recursive : MonoBehaviour
{
public int levelNum = 0;
public int totalLevels = 0;
void Start()
{
RecursiveMethod(transform);
Debug.Log("Total Levels : " + totalLevels);
}
void RecursiveMethod(Transform obj)
{
levelNum++;
Debug.Log("Level : " + levelNum);
foreach (Transform child in obj)
{
RecursiveMethod(child);
}
totalLevels = levelNum;
levelNum--;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vinicius Cardoso |
