Some people, especially beginners, have a hard time wrapping their heads around a concept that may seem daunting at first but is actually pretty simple once you understand the core mechanics of it: generics in C#. I still remember staring at List<int> when I started out and wondering what the hell the <int> part was doing there. It turns out it's one of the most useful features in the whole language, and you've been using it since your first GetComponent call!
Let me try to explain this the best I can...
You've Been Using Generics All Along
Take a look at code you've probably already written:
List<string>- a list that holds stringsDictionary<string, int>- a dictionary mapping strings to intsGetComponent<Rigidbody>()- find a Rigidbody on this objectJsonUtility.FromJson<SaveData>(json)- turn JSON back into aSaveDataObjectPool<Bullet>- a pool that holds bullets
Every one of those angle-bracket bits is a generic. The thing in the brackets says which type to work with, and the code around it works the same no matter what you put there. Now let's learn to write our own.
What Exactly Are Generics In C#?
Generics let you write code once and use it with many different types. Instead of hard-coding a type like int, you write a placeholder, usually called T, and fill in the real type later when you use it.
write the code once with T → fill in a real type when you use it → the compiler checks everything for that type
That last part matters. A generic is fully type-safe. Put a string in a List<int> and the compiler stops you before the game even runs.
Generic Classes: Write It Once!
Here's the problem that generics solve. Say you want a very simple box that holds a value. Without generics, you'd write a separate class for every type, or give up type safety. Here's the generic way:
// Without generics: a separate class for every type
public class IntBox
{
public int value;
}
public class StringBox
{
public string value;
}
// With generics: one class that works with any type
public class Box<T>
{
public T value;
}
// Using it
Box<int> number = new Box<int>();
number.value = 5;
Box<string> word = new Box<string>();
word.value = "Hello";
The T in Box<T> is a placeholder that gets replaced when you use the class. Box<int> is a box of ints, and Box<string> is a box of strings, from a single class. Fix a bug in Box<T> once, and every version gets the fix.
Generic Methods In C#: One Method, Many Types
You don't need a whole generic class to benefit. A single method can be generic too. These generic methods in C# put the placeholder right after the method name:
using System.Collections.Generic;
using UnityEngine;
public static class Utility
{
public static T GetRandom<T>(List<T> items)
{
if (items.Count == 0)
{
return default; // the "empty" value for T: null, 0, false, and so on
}
return items[Random.Range(0, items.Count)];
}
public static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
}
// Using them: Unity works out T for you
string name = Utility.GetRandom(names);
int number = Utility.GetRandom(numbers);
GetRandom picks a random item from any list: names, numbers, enemies, spawn points. Notice you don't have to write GetRandom<string> when calling it. C# figures out T from the list you pass in. And that default keyword gives back the "empty" value for whatever T turns out to be, which is null for objects and 0 for numbers.
Generic Constraints In C#: Setting Rules For T
There's a catch with a totally open T. And since it could be anything, C# won't let you assume anything about it. You can't call .transform on a T, because an int doesn't have one. That's where generic constraints in C# come in. A constraint tells the compiler what T is allowed to be:
public static T FindClosest<T>(List<T> items, Vector3 from) where T : Component
{
T closest = null;
float shortest = float.MaxValue;
foreach (T item in items)
{
float distance = Vector3.Distance(from, item.transform.position);
if (distance < shortest)
{
shortest = distance;
closest = item;
}
}
return closest;
}
// Using it
Enemy nearest = Utility.FindClosest(enemies, transform.position);
The where T : Component part says "T must be a Unity Component." Now the compiler knows every T has a transform, so the method works for enemies, pickups, spawn points, or anything else attached to a GameObject. It won't accept an int, which is exactly the point.
The constraints you'll see most often:
where T : class-Tmust be a reference typewhere T : struct-Tmust be a value type, likeintorVector3where T : new()-Tmust have a parameterless constructor, so you can writenew T()where T : SomeBaseClass-Tmust inherit from that class, likeComponentabovewhere T : ISomeInterface-Tmust implement that interface
A Real Unity Example: The Generic Singleton
So when do you use generics then? If you've read the Singleton article, you know every manager repeats the same boilerplate. A generic base class writes it once:
using UnityEngine;
public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
public static T Instance { get; private set; }
protected virtual void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = (T)this;
}
}
// A real manager, built on top of it
public class AudioManager : Singleton<AudioManager>
{
public void PlayJump()
{
Debug.Log("Boing!");
}
}
// Anywhere in your game
AudioManager.Instance.PlayJump();
Each manager inherits the instance handling for free, and AudioManager.Instance is already typed as an AudioManager, so there's no casting. Whether you should use Singletons at all is a debate for that other article. The point here is how generics and constraints combine to remove repeated code.
Generics Gotchas In Unity
A few things that may trip people up:
- You can't attach a generic MonoBehaviour directly! A class like
Singleton<T>is a template, not a finished component. You attach a concrete one, likeAudioManager. - Don't over-generalize. If you only ever use one type, a generic just adds noise. Reach for one when you notice yourself copy-pasting the same logic for different types.
- Open
Tmeans few assumptions. You can't usenew T(), call type-specific members, or compare freely until a constraint allows it. - Names matter. A single placeholder is just
T. With several, use descriptive names likeTKeyandTValue.
So Which Approach Should You Use?
Here's a little overview that may shine some light on when to use it:
- The same logic repeated for different types → generics in C#
- One reusable function for many types → one of those generic methods in C#
- A reusable container or manager → a generic class
- The method needs to use something about
T, like.transform→ generic constraints in C# - Only ever one type → skip generics, keep it simple
- A generic MonoBehaviour → make a concrete subclass to attach
The question that settles it is simple: "am I about to write this same code a second time for a different type?" If yes, make it generic.
Wrapping Up
Generics may look pretty intimidating until you realize T is just a blank you fill in later. You've been using them with every List and every GetComponent. Now you can write your own: a generic class for reusable containers, generic methods for utilities, and constraints to tell the compiler what you need from T. Write it once, use it everywhere, and let the compiler catch the mistakes!
~happy Coding!


No comments:
Post a Comment