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
MediumWrite one generic helper for the shock tower's crates and lamps.
- In
Helpers.cs, write the static classHelperswith publicInRange<T>(IEnumerable<T> items, Vector3 center, float range)for components: aList<T>of the items at mostrangeaway. - In
Pulse, on Space, give every Rigidbody in range an upward impulse oflift. - 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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground