Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity ScriptableObjects - Read-only fields

Say I have a ScriptableObject Item:

public class Item : ScriptableObject
{
    public new string name;
    public string description;
    public Sprite sprite;
}

The only issue is that the fields can be modified:

Item item = new Item();
item.description = "Overwrite";

I want them to be readonly. I found this workaround using properties:

public class Item : ScriptableObject
{
    [SerializeField] private new string name;
    [SerializeField] private string description;
    [SerializeField] private Sprite sprite;

    public string Name => name;
    public string Description => description;
    public Sprite Sprite => sprite;
}

The only issue is that this effectively doubles the length of all of my ScriptableObjects and seems cumbersome. Is there another preferred way to make ScriptableObject fields readonly without the extra code and still serializing fields?

like image 672
Isaac Thompson Avatar asked Oct 15 '25 14:10

Isaac Thompson


1 Answers

You can use Field-Targeted Attributes:

public class Item : ScriptableObject{
    [field: SerializeField] public string Name { get; private set; }
    [field: SerializeField] public string Description { get; private set; }
    [field: SerializeField] public Sprite Sprite { get; private set; }
}
like image 141
Lyrca Avatar answered Oct 18 '25 19:10

Lyrca