Welcome to my first tech blog! I've been using Unity personally and professionally for over 4 years and along the way I've 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 future tech blogs I want to share my solutions for these problems, and also my experience and lessons learned about Unity in general.
One of the limitation of Unity's inspector is that it doesn't support dynamic type of 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 may have something like this.
The issue is that when you go to the inspector for Mage, first, you cannot choose which subclass of Ability, second even if you assign it a sub class of say FireBall through some EditorGUI 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 gonna create something called AbilityFactory class, and the Mage class will now looks like this.
The idea is to have a factory class that allows you to pick a dynamic type for 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!
All 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. Magic happens in DrawPrimarySpell, which uses reflection 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!