We have some rather complex object setups for our game objects/prefabs (at least given their amount) so most of our scripts are set to automatically resolve references if not manually set, thus allowing quickly setting up units just by dropping in modules without having to resolve obvious references.
For example, the controller module will look for weapon, engine, AI and HP scripts in the object’s hierarchy unless specifically given them.
if ( weapons.Length == 0 )
weapons = transform.GetComponentsInChildren.<Weapon_Base>();
if ( engine == null )
engine = transform.GetComponentInChildren.<Engine_Thruster>();
if ( operator == null )
operator = transform.GetComponentInChildren.<Operator_Base>();
if ( bodyHub == null )
bodyHub = transform.GetComponentInChildren.<Body_Hub>();
The Hierarchy is rather flat, like this:
> root
| o Controller Script
| o Body Script
| o Engine Script
|-> Colliders
| |-> BoxCollider
| \-> ...
|-> WeaponA Container
| o WeaponA Script
\-> WeaponB Container
o WeaponB Script
Now we’d like to extent the complexity of our objects with sub-components - think of independent turrets, destroyable engines, the like. This means that a component would scan the hierarchy for possible script references, but only until it hits another component of its kind - for example, the root controller would still store all weapons but those in a sub-hierarchy of say a turret controller.
> root
| o Root Controller Script
| o Root Body Script # belongs to root controller
|-> WeaponA Container
| o WeaponA Script # belongs to root controller
|-> Turret Root # root controller won't enter here
| | o Turret Controller Script
| | o Turret Body Script # belongs to turret controller
| \-> WeaponB Container
| o WeaponB Script # belongs to turret controller
\-> WeaponC Container
o WeaponC Script # belongs to root controller
So what we’d need is some way to walk through the hierarchy, just as one would walk through directories in a filesystem, or a way to discern whether between the searching component and the found one there is a specific component in between. Or is there even an inbuilt function for this, to limit the depth of searching components?