Menu
CoddyTech

Generic Helpers

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

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

A shock tower stands in the yard. When Space is pressed it sends out a pulse: crates within 4 of it are thrown up, and lamps within 4 light up. Lamp.cs is ready, with TurnOn(). Write one helper that finds both:

  • In Helpers.cs, write a static class Helpers with a generic method InRange<T>(IEnumerable<T> items, Vector3 center, float range) for any component type. It returns a List<T> of the items whose position is at most range from center.
  • In Pulse.cs, when Space is pressed: every Rigidbody in the scene within range of the tower gets an upward impulse of lift, and every Lamp within range is turned on. Use InRange for both, on the arrays FindObjectsByType gives you.

Press Play, press Space, then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;

// Helpers.InRange<T>: the items within range of a point
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