- Home /
How do I cleanly check if there is a specific component in a parent x positions above the current component in the hierarchy?
Currently I am avoiding 3 children below the parent via gameObject.GetComponentsInChildren but this is causing issues if I have a second child from the highest parent object or the first few children as it appears to go off Depth-First search.
Where the hierarchy looks something like
Parent
|- Child-A
--|- Child-A1
----|- Child-A2
------|- Child-A3
|- Child B
void Start()
{
wiresInSys = new List<ElectricalWire>(gameObject.GetComponentsInChildren<ElectricalWire>());
systemOn = true;
}
void interact()
{
if(systemOn)
{
systemOn = false;
if(wiresInSys.Count > 4)
{
for(int i=3; i<wiresInSys.Count; i++)
{
Debug.LogWarning(wiresInSys[i] + " set electricity off");
wiresInSys[i].electricityMode = false;
}
}
}
}
How could I go about doing this in a manner that captured the children A, A1, A2, and B, as well as any children B might have that are within 3 levels from Parent? Just a note that the children are all prefabs so they have the same name.
Sorry for formatting (editting enabled if anyone wants to edit it better :) ) and if noobish question.
Sounds like you've created an awfully complex situation for yourself. If it were me, I'd figure out some way to tag the game objects I wanted to find as I was instantiating them. You can change the name, the tag, or even add scripts at runtime while you are Instantiating() the objects. If the ones you care about all have the same name or tag, you can walk the Transform tree recursively and grab those you want. If you put a script on all the ones you care about, you can use GetComponentInChildren() using the script you added to find the objects. From a reference to a script, you can get to the game object or transform of that object.
Tags are a possibility, but to me the situation looks like the children in the 3rd level have some functionality that the other GOs don't have. I would try to think for a way to add appropriate scripts to the GOs at instantiation, so GetcomponentsInChildren can be used with just the specific script.
Then there's always the possibility of doing a custom recursive search.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Finding objects with TextMeshPro component. 1 Answer
Step through debug in Visual Studio not updating Unity hierarchy 0 Answers