- Home /
Make a field in inspector hold inheriting classes
Hello,
I was wondering if it was possible for a field in the Inspector to change between different classes that extend the given field type.
What I mean is, I have a Weapon class, I also have Gun and Melee, which both extend Weapon. Gun and Melee have their own specific variables but also use some of Weapon's variables.
What I want is for some other script, to have a public variable of type Weapon, and I want to be able to be able to use either a Gun or a Melee inside the field in the Inspector. (So that I am able to edit the variables for that weapon in the inspector no matter what the weapon "type" is).
Here's a quick example
public class Weapon{
public string weaponName;
}
public class Melee : Weapon{
public float range;
}
public class Gun : Weapon{
public float ammoCapacity;
}
public class Attack : MonoBehaviour {
//Can I (inside the Inspector), use a Gun or Melee instead of being forced to a basic Weapon
public Weapon weapon;
}
Thanks!
Answer by UnityCoach · Jan 06, 2017 at 01:40 PM
You could make your weapon class a ScriptableObject. Then you would have to create weapons as assets and drag and drop them :
[CreateAssetMenu (fileName = "New Generic Weapon.asset", menuName = "Generic Weapon")]
public class Weapon : ScriptableObject
{
public string weaponName;
}
[CreateAssetMenu (fileName = "New Melee.asset", menuName = "Melee")]
public class Melee : Weapon
{
public float range;
}
[CreateAssetMenu (fileName = "New Gun.asset", menuName = "Gun")]
public class Gun : Weapon
{
public float ammoCapacity;
}
The only limitation, is that ScriptableObject are only references, so changing one changes them all. Which can also be handy.
The only limitation, is that ScriptableObject are only references, so changing one changes them all. Which can also be handy.
By that, do you mean, that I have to create a new script/class for each separate weapon that I want to make?
Ok, I found a great tutorial for this! https://www.youtube.com/watch?v=ItZbTYO0$$anonymous$$nw Thanks a lot!
Not a new script/class, but a new asset. Though, using the implementation suggested by @Adam-$$anonymous$$echtley solves this.
Answer by Adam-Mechtley · Jan 06, 2017 at 07:40 AM
What you're asking about here is polymorphic serialization, which is not supported. I have answered similar questions e.g., here, discussing possible workarounds.
Scriptable Objects was the way to go! Thanks for the help! I ended up using this video to make my Scriptable Objects https://www.youtube.com/watch?v=ItZbTYO0$$anonymous$$nw
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Custom classes, inheritance and the inpector 0 Answers
Custom ordering of variables in inspector when using base and derived classes 1 Answer
HideInInspector with inherited variables 1 Answer
Child of Text class not showing added public variable in insepctor 2 Answers