- Home /
Does the Unity Inspector support Inheritance?
Not to be confused with this related question, I know Unity does Inheritance but I'd like to leverage it in the Inspector.
I'd like to be able to switch the action to be performed on-the-fly using buttons in the GUI. So, I've got a class AbstractAction
that inherits from MonoBehaviour which has a single abstract method DoAction
. I've written a couple of scripts that inherit from AbstractAction and override the method, and I want to assign them to specific slots in the GUI using the inspector (similarly to how I assign the Texture2D
s for the buttons themselves).
public class MyGui : MonoBehaviour {
public Texture2D[] buttons;
public AbstractAction[] actions;
private int selectedAction;
void OnGUI() {
selectedAction = GUILayout.SelectionGrid(0, buttons, 2);
}
public void DoSelectedAction() {
actions[selectedAction].DoAction();
}
}
My problem is, the array is showing up fine in the Inspector (with elements "None (Abstract Action)"), but I cannot assign my subclasses of AbstractAction to them. Is there a way around this? I've tried using both an actual abstract
parent, and a normal class with a virtual
method.
Thanks in advance
I recall you need to make it serializable to make it show up there. But I'm not sure actually so posting it as comment/idea ins$$anonymous$$d of answer.
Answer by coastwise · Dec 09, 2010 at 11:10 PM
Turns out this is possible to do. My problem was that I was attempting to drop the script itself into the array in the Inspector. Instead, it was expecting a GameObject
(or prefab) that has an AbstractAction script (or a script that inherits from it) attached.
Ultimately I created a prefab for each action that contains both the texture and the action script subclass, and therefore only need a single array to define them both in the GUI. Clean, functional and properly captures the relationship between the image and the action!
Your answer

Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Values lost? 1 Answer
Check if gameobject has script with inheritance 2 Answers
c# enum wont show in inspector 3 Answers