GetComponents
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 9 of 64.
GetComponent<T>() returns the first match. GetComponents<T>() returns every match on the object as an array, and GetComponentsInChildren<T>() every match on the object and everything under it. With an interface as T, one call collects every part that can do something, whatever its class. Here the machines of a factory are children of the Factory object, and each part that runs on power implements IPowered:
public interface IPowered
{
void SetPower(bool on);
}public class Generator : MonoBehaviour
{
public GameObject factory;
public void Switch(bool on)
{
IPowered[] parts = factory.GetComponentsInChildren<IPowered>();
foreach (IPowered part in parts)
{
part.SetPower(on);
}
Debug.Log(parts.Length + " parts powered");
}
}A Lamp switches its Light, a Fan starts turning, a Conveyor starts moving, each in its own SetPower. A machine with a Lamp and a Fan on one object counts twice, since each component is a separate match. The Generator never names them, so a Siren that implements IPowered, added under the Factory later, is switched on by the next Switch.
GetComponentsInChildren includes the object you call it on, and it skips children that are inactive unless you pass true: GetComponentsInChildren<IPowered>(true). GetComponents looks at the one object only, which suits parts that sit side by side, such as a light and a buzzer on one door.
Challenge
EasyLet every part of the robot show a hit.
- In
IHitReaction.cs, declarepublic interface IHitReactionwithvoid React(int damage);. - Make
Flash,RecoilandSparksimplement it: rename each method topublic void React(int damage). - Recoil moves
0.5f * damageback; Sparks throwsdamagesparks. - In
TakeDamage, callReact(amount)on everyGetComponentsInChildren<IHitReaction>(), then logReactions: 3(their count).
Press Play, press Space, then click. Then Check.
Try it yourself
using UnityEngine;
public class Health : MonoBehaviour
{
public int hp = 10;
public void TakeDamage(int amount)
{
hp -= amount;
GetComponentInChildren<Flash>().Show();
}
}
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground