- Home /
Problem with finding compnent of immidate children
Hi all im having problems finding the components of immediate children.
Im trying to make a "power" system that starts at one parent object at say power 10, then as it goes through its children (all with the same script) they divide up the power.
transform.GetComponentsInChildren() will not work because firstly it calls its own LocalPower script even though it is not a child, and secondly it calls all of the sub children. I learnt this enough from google.
so next i tryed to use foreach (Transform child in transform) { nNode = child.transform.GetComponent (); }
However not all of its child objects have the script, as only power 'nodes' and things that use power use the script.
I tried to make a list and only add nNode if it found the script but could not find a way to do that- and im feeling pretty dicy about the whole thing.
First post, im a total noob im afraid, thank you!
Answer by robertbu · Mar 18, 2014 at 03:20 AM
You can make either one work. Start with the second one first. Just check to see if you get a null back from GetComponent():
foreach (Transform child in transform) {
if (child != transform) {
SomeScript nNode = child.GetComponent<SomeScript>();
if (nNode != null) {
// Do whatever with nNode
}
}
}
As for the other one, just check the transform.parent:
SomeScript nNodes[] = gameObject.GetComponentsInChildren<SomeScript>();
foreach (SomeScript nNode in nNodes) {
if (nNode.transform.parent == transform) {
// Do whatever with nNode
}
}
Worked fantastic! I need to get my head into programmer mode, i had not thought to check if the child was the parent.