'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?
Solution 1:[1]
You can initialize the fields as properties directly and add the get method to it. set method is by default set to private set;. It restricts any external modifications of the properties. These properties can be set privately, i.e. they are accessible and modifiable within the script.
public string Name { get; }
public string Description { get; }
public Sprite SpriteObj { get; }
Note: Naming convention of properties is that they start with an uppercase letter. Changing the property name to SpriteObj so that it doesn't clash with the inbuilt component name.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Geeky Quentin |
