Welcome to my first tech blog! I’ve been using Unity personally and professionally for over 5 years and along the way encountered many road blocks. I could find solutions for some of them searching online, but that’s not always the case. We’ve all come across issues that rarely anyone talks about and there’s no solution available online. So in my blogs I want to share my solutions for these problems, and also my experiences and lessons learned about Unity in general.
One of the limitations of Unity’s inspector is that it doesn’t support dynamic type for a field. For example, in your game, you have a class called Mage, and it has a public variable of Ability, which is a base class for different kinds of actual abilities as below.
Now in your Mage class you might have something like this.
When you go to the inspector for Mage, there are two issues (1) you cannot choose which subclass of Ability, (2) even if you assign it a subclass of say FireBall through code, the inspector does not show appropriate fields for that dynamic type.
I came up with a pattern that allows you to pick dynamic type and display it properly in the inspector.
Here’s how it works. First, instead of using Ability as PrimarySpell, we’re going to create something called AbilityFactory class, and the Mage class will now look like this.
The idea is to have a factory class that allows you to pick a dynamic type for the spell, and also displays the fields properly depending on which dynamic type is selected. And the factory will create the appropriate run-time Ability in Awake. Here’s what the factory looks like:
What it does is to have an enum representation for each dynamic ability type, and also an instance for each dynamic type and return the corresponding instance when given an ability type. All we have to do when we create a new ability type is to add 3 lines in the factory: new enum, new instance, and new case in switch statement. So once we setup this pattern, the overhead when creating a new ability class is very low.
Last but not least, we need a custom editor class to make the magic happen, to make our mage have a dynamic spell!
OnEnable and OnInspectorGUI here are fairly standard. The magic happens in DrawPrimarySpell, which uses reflections to find the corresponding Ability instance in the factory and then displays its serialized properties accordingly!
There you have it! Dynamic property field! It takes a little bit of time to set it up initially, but it makes designing and tweaking part of the game much more convenient!
Feel free to leave a comment below or e-mail me personally if you have any question!