Menu
CoddyTech

GetComponents

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 8 of 50.

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

The training robot should show every hit. Health.cs on the Robot counts hp, and three parts can react: Flash on the Head turns it red, Recoil on the Robot jolts it back, and Sparks on the Antenna throws sparks. Space hits the robot for 1 and a click hits it for 2 (Trainer.cs, ready). Right now Health tells only the head.

  • In IHitReaction.cs, declare an interface IHitReaction with one method, void React(int damage).
  • Make Flash, Recoil and Sparks implement it: each one's method becomes React(int damage). Flash does what it did. Recoil jolts the robot 0.5 units back (+z) per point of damage, and Sparks throws one spark per point of damage.
  • In Health's TakeDamage, after hp drops, call React(amount) on every IHitReaction on the Robot and its children, found with one GetComponentsInChildren call, and log how many reacted, as Reactions: 3.

Press Play, hit the robot with Space and with a 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();
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Game Architecture in Unity