Search code examples
unity-game-enginecustom-attributesscriptable

Make Unity attributes like [range] work together with inheritance in ScriptableObjects


Let's use the following code:

public abstract class ItemTemplate : ScriptableObject
{
    public Sprite Sprite;
    public DataKeeperScript.ItemCategories ItemCategory;
    public string Name;
    [Range(0, 100)]
    public int Rarity;
}

[CreateAssetMenu(fileName = "New FoodTemplate", menuName = "ItemTemplates/Food")]
public class FoodTemplate : ItemTemplate
{
    [Range(0, 100)]
    public int HungerFillAmount;
}

When I create a "Weapon" scriptableObject asset in the editor I can also fill in the properties from the parent "Item" class, which is great.

But why does the [range] attribute from the parent "Item" class not work when I create the scriptable object asset for a "Weapon" in the editor? The range for the HungerFillAmount of the "Weapon" class itself also does not work. Can't figure it out. Can I put some magic attribute somewhere to make the attributes work for the inherited children as well? Thanks for thinking with me! :)


Solution

  • It's fixed! I first had all the child classes in one big FileTemplate.cs file, but that also gave the problem that the Editor sometimes said the associated script could not be found. Now I created seperate files, so I have the ItemTemplate.cs for the abstract files and for the childs FoodTemplate.cs, WeaponTemplate.cs and so on. I did this earlier to fix the script not found error, but only now I see it also fixed this issue.