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
MediumA 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 classHelperswith a generic methodInRange<T>(IEnumerable<T> items, Vector3 center, float range)for any component type. It returns aList<T>of the items whose position is at mostrangefromcenter. - In
Pulse.cs, when Space is pressed: every Rigidbody in the scene withinrangeof the tower gets an upward impulse oflift, and every Lamp withinrangeis turned on. Use InRange for both, on the arraysFindObjectsByTypegives 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types