- Home /
Search children first hierachy
Hey there, I have a GameObject which has for panel as childs assigned to it, each panel has 3 images assinged as childs. Now I want the first gameobject to active the panels, one for every play in the game (amount of players is stored in a dictionary) For this I created the following script:
void Start()
{
base.Start();
// assign panels
Image[] panelChildren = gameObject.GetComponentsInChildren<Image>();
int currentIndexPortrait = 0;
foreach (Image charScore in panelChildren)
{
if (Leaderboards.scoreList.ScoreDict.ContainsKey(currentIndexPortrait) != false)
{
charScore.gameObject.SetActive(true);
}
else
{
charScore.gameObject.SetActive(false);
}
currentIndexPortrait++;
}
}
The Problem I am facing right now is that, if two players are in the game only one panel gets activated, all others will be deactivated. The reason for that seems to be that GetComponentsinChildren goes through the entire hierachy of children and therefore finds more images which are chldren of the first panel.
Is there a way to let my code only search through the first layer of children and not include childs of childs ?
Answer by DanSuperGP · Jan 22, 2015 at 06:45 PM
If you want to only iterate through one level of children, the easiest way to do it is to simply iterate through the transform instead of doing GetComponentsInChildren
int currentIndexPortrait = 0;
foreach( Transfom childTrans in transform)
{
Image charScore = childTrans.GetComponent<Image>();
if(charScore != null)
{
if (Leaderboards.scoreList.ScoreDict.ContainsKey(currentIndexPortrait) != false)
{
charScore.gameObject.SetActive(true);
}
else
{
charScore.gameObject.SetActive(false);
}
currentIndexPortrait++;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613181206im_/https://answers.unity.com/themes/thub/images/avi.jpg)