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!

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.

What you’re asking about here is polymorphic serialization, which is not supported. I have answered similar questions e.g., here, discussing possible workarounds.