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

574 Views Asked by At

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! :)

2

There are 2 best solutions below

0
On BEST ANSWER

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.

1
On

If I put your code in a file called FoodTemplate.cs and create an instance of Food, the range attributes work. First I used another file name and then it didn't work so I guess the problem is related to the file name being wrong? What file name did you use?

enter image description here