- Home /
Polymorphic weapon system
Just coming back to using Unity after a long period of time in .NET web development.
I'm prototyping a little top-down shooter, and I'd like to be able to switch out behaviours in the inspector with polymorphism.
My current example is something like this:
The player has a Combat component, which handles input and has a public Weapon variable. Weapon is an interface with a "Fire" function.
I have an implementation of Weapon called "Assault Rifle" which has particular behaviours when Fire is called.
The ideal here is that underneath the Combat component in the inspector, I could simply drag and drop any script that implements Weapon.
I feel like I'm misunderstanding some key Unity principles here. Any help would be really appreciated.
Answer by Bunny83 · Apr 14, 2018 at 01:52 PM
Using an interface does work when you use GetComponent. However references to interfaces can't be serialized by Unity. If you want to be able to assign a behaviour by drag&drop you have to use a baseclass with a virtual / abstract method instead.
Thanks for the reply!
I've managed to get this far. The issue, however, is that I can only drag and drop scripts that exist within the scene.
I'd like to be able to drag, for example, my "AssaultRifle" script from my project scripts folder, and into the Weapon property on my player.
EDIT: Do I need to just create a lot of empty game objects with my weapon scripts on them, and use such prefabs?
Well you can't store a reference to a "class type" in a variable. (Well technically System.Type would work, but this can not be serialized ^^). If your weapon implementations don't require to be a $$anonymous$$onoBehaviour and to be attached to a gameobject you can derive your base class from ScriptableObject. ScriptableObjects can be stored as assets in the project and referenced by other serialized objects.
Also keep in $$anonymous$$d that you can attach multiple weapon derived $$anonymous$$onoBehaviours scripts to the same gameobject. Though dragging the components to variables involves using two inspectors if the weapon scripts are not on the same gameobject as your referencing script.
To drag individual scripts onto variables you have to drag the script header from the inspector like in this example:
Your answer
Follow this Question
Related Questions
Assigning child script to parent field in Inspector 1 Answer
Inspector - editing array of polymorphic objects? 2 Answers
Show DefaultInspector on child classes in list 0 Answers
Draw Inspector For Most Derived Type Of Collection Elements 3 Answers
Serializable class with access to its Monobehaviour host 2 Answers