I’ve recently started needing to have multiple game states within my game, and decided to set object hierarchies within the scene inactive / active to manage this state.
I was initially very confused by the fact that GameObject.GetComponentInChildren() doesn’t work for components on inactive GameObjects.
Though it is mentioned in the online documentation it’s far from obvious - this is the sort of behaviour that should be printed in massive bold letters or under a “please note” heading… (Unity - Scripting API: Component.GetComponentInChildren)
After a bit of googling / poking about in forums etc. I couldn’t find any “standard” way (i.e. out of the box unity function) to do it…
…but I did find enough info to write my own code to do it; and since I had not found any conclusive answers I decided to post a question and then answer it to help anyone else who might be stuck with the same issue
So whilst GetComponentInChildren() doesn’t check the components of inactive GameObjects, it turns out that GetComponent() does check the components of an inactive obejct.
The obvious solution to my problem was to write code to traverse a GameObject hierarchy by hand and call GetComponent() manually on each GameObject.
Here’s the code:
///////////////////////////////////////////////////////////////
/// <summary>
/// Game object tools.
/// </summary>
///////////////////////////////////////////////////////////////
static public class GameObjectTools
{
///////////////////////////////////////////////////////////
// Essentially a reimplementation of
// GameObject.GetComponentInChildren< T >()
// Major difference is that this DOES NOT skip deactivated
// game objects
///////////////////////////////////////////////////////////
static public TType GetComponentInChildren< TType >( GameObject objRoot ) where TType : Component
{
// if we don't find the component in this object
// recursively iterate children until we do
TType tRetComponent = objRoot.GetComponent< TType >();
if( null == tRetComponent )
{
// transform is what makes the hierarchy of GameObjects, so
// need to access it to iterate children
Transform trnsRoot = objRoot.transform;
int iNumChildren = trnsRoot.childCount;
// could have used foreach(), but it causes GC churn
for( int iChild = 0; iChild < iNumChildren; ++iChild )
{
// recursive call to this function for each child
// break out of the loop and return as soon as we find
// a component of the specified type
tRetComponent = GetComponentInChildren< TType >( trnsRoot.GetChild( iChild ).gameObject );
if( null != tRetComponent )
{
break;
}
}
}
return tRetComponent;
}
}
I’ve not bothered to do an equivalent for GetComponentsInChildren() but it should be a simple enough extension of the code above.