Menu
CoddyTech

Generic Helpers

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 44 of 64.

Some helpers are the same for every type: get a component or add it, pick a random entry from an array. A generic method writes them once, with the type as a parameter T that each call fills in:

public static class Helpers
{
    public static T GetOrAdd<T>(this GameObject go) where T : Component
    {
        if (!go.TryGetComponent(out T found)) found = go.AddComponent<T>();
        return found;
    }

    public static T RandomItem<T>(T[] items)
    {
        return items[Random.Range(0, items.Length)];
    }
}
Rigidbody body = crate.GetOrAdd<Rigidbody>();
Color paint = Helpers.RandomItem(colors);
GameObject enemy = Helpers.RandomItem(enemyPrefabs);

where T : Component is a promise about T, and it decides what the method may do with it. AddComponent only takes components, so without the constraint the compiler refuses go.AddComponent<T>(); with it, any component works, Unity's Rigidbody or your own scripts. The constraint also gives you every member of Component on a T, such as .transform and .gameObject. A crate that already has a Rigidbody gets that one back, and nothing is added.

RandomItem has no constraint, because it never touches T: it works for colors, strings and prefabs alike. You rarely write the type at the call: from colors, a Color[], the compiler works out that T is Color. A method that takes IEnumerable<T> instead of T[] accepts arrays and Lists both, including the arrays FindObjectsByType<T> returns.

challenge icon

Challenge

Medium

Write one generic helper for the shock tower's crates and lamps.

  1. In Helpers.cs, write the static class Helpers with public InRange<T>(IEnumerable<T> items, Vector3 center, float range) for components: a List<T> of the items at most range away.
  2. In Pulse, on Space, give every Rigidbody in range an upward impulse of lift.
  3. Then call TurnOn() on every Lamp in range.

Press Play and press Space: the near crate jumps. Then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;

// Helpers.InRange<T>: the items within range of a point

All lessons in Game Architecture in Unity

Practice on your own: Unity playground