Menu
CoddyTech

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 icon

Challenge

Easy

Let every part of the robot show a hit.

  1. In IHitReaction.cs, declare public interface IHitReaction with void React(int damage);.
  2. Make Flash, Recoil and Sparks implement it: rename each method to public void React(int damage).
  3. Recoil moves 0.5f * damage back; Sparks throws damage sparks.
  4. In TakeDamage, call React(amount) on every GetComponentsInChildren<IHitReaction>(), then log Reactions: 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

Practice on your own: Unity playground