Nerd For Tech
Published in

Nerd For Tech

Using C# Generic Types With Scriptable Objects in Unity

Using Class Inheritance to Pull The Wool Over Unity’s Eyes

Technically untrue.

I recently watched a brilliant presentation on Game Architecture with Scriptable Objects from Ryan Hipple, where he demonstrated a useful pattern he calls the Runtime Set. It’s a useful way to keep track of all of the active objects of a given type in the scene. If you’ve ever needed to keep track of how many enemies remain in a wave, or which buildings have been built in a player’s warcamp, this is a great way to have that information tracked and available to any class or method that wants it without hard dependencies or extra code.

The tricky part is, he doesn’t fully explain the implementation of the Runtime Set. He just shows a simplified version of the core object. Here’s the code:

Ryan Hipple, Unite Austin 2017

This is great, right? If I want to keep track of all the actors in my tactical rescue game, all I need is to create a new .asset out of a specific type of this generic. Like so:

But if you saw the spoiler at the top… no. Unity doesn’t like that.

Generic MonoBehaviours are not supported?! This isn’t a MonoBehaviour at all! What sorcery did Ryan Hipple employ to make this work?

WTH, Unity?!

Okay, clearly we’re going to need a different approach. Unity doesn’t want to create an instance of a generic class, so we’ll have to dress our generic class in sheep’s clothing.

Let’s create a costume. It doesn’t have to be complicated — just enough of a exterior façade to fool Unity into giving us what we want.

Hooooowwwll — er, I mean… Baaa!

Wow. Yeah, it’s that simple. ActorRuntimeSet inherits all the methods and fields of its parent class— in this case, the no-longer generic RuntimeSet<Actor>. So, there’s no need for a body. We’ve already defined that.

Now, we can create our .asset with the modified code:

And here’s the result:

I can tuck this asset into a serialized field on my Actor prefabs, and then instruct them to add and remove themselves from the list whenever they are enabled or disabled:

That’s the gist: by inheriting a generic class to a standard class you can sneak generic types under Unity’s notice. Once you have an asset built you can let any object refer to it to get an updated list of the items the list is built to track.

Can you think of other ways to use this trick? Drop a comment below and let me know!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Micha Davis

Micha Davis

Unity Developer / Game Developer / Artist / Problem Solver