- Home /
Question by
lamhoyin · Mar 02, 2020 at 07:22 AM ·
c#uiunityeditor
Search child under parent in self
I got my game object create like the image below :
My code is compile in PanelStatus and I wish to control the object UnitImage.
But while I search from child I could only get the first layer which means only the PanelUnit have been returned.
Here is my code :
Image UnitImageImage;
const string UnitImageObjectName = "UnitImage";
void Awake()
{
foreach(Transform child in transform)
{
switch (child.name)
{
case UnitImageObjectName:
UnitImageImage = child.GetComponent<Image>();
break;
default:
Debug.Log(child);
break;
}
}
}
2020-03-02-151351.png
(1.9 kB)
Comment
Best Answer
Answer by ShadyProductions · Mar 02, 2020 at 07:38 AM
You can use Unity's inbuild method 'GetComponentsInChildren':
private GameObject GetChildByName(GameObject parent, string childName, StringComparison stringComparison = StringComparison.InvariantCulture)
{
return parent.GetComponentsInChildren<Transform>()
.Where(a => a.gameObject.GetInstanceID() != parent.GetInstanceID() &&
a.name.Equals(childName, stringComparison))
.Select(a => a.gameObject)
.FirstOrDefault();
}
private GameObject[] GetChildrenByName(GameObject parent, string childName, StringComparison stringComparison = StringComparison.InvariantCulture)
{
return parent.GetComponentsInChildren<Transform>()
.Where(a => a.gameObject.GetInstanceID() != parent.GetInstanceID() &&
a.name.Equals(childName, stringComparison))
.Select(a => a.gameObject)
.ToArray();
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612224241im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
SetBool and SetTrigger not work on UI button click in unity 0 Answers
Scaling RectTransform to fit screen size in code 1 Answer
error CS0029: Cannot implicitly convert type 'string' to 'int'... I EVEN ADDED .ToString(); 1 Answer
Full Screen Toggle will not work. 1 Answer
Multiple Cars not working 1 Answer