Inspired by a question posted on Reddit (Read Only Parameter with SerializeField), I realized that I don’t have a way of communicating to other developers on my team which fields are not designed to be modified while playing in the editor! So I decided to solve this problem by adding a new attribute [Immutable] which disables fields in the inspector.
The attribute has two usage patterns: [Immutable], which causes the field to become greyed-out (disabled) when the editor is running, and [Immutable(false)], which causes the field to be greyed-out always (the optional parameter is called isEditable). The attribute is very simple, but useful. Use it well! You might also find this a nice way to learn the syntax for writing your own attributes and property drawers if you haven’t explored that yet.
[SerializeField] [Immutable] private int _inventorySize = 10; [SerializeField] [Immutable(false)] private int _inventorySearchCount = 3;
This first example is indicative of a system which initializes the inventory system when Awake is called (instantiating enough slots, etc). We don’t want anyone changing this at runtime from inside the editor.
The second is something I wanted to be able to do to protect myself from forgetting how something works without exposing the system to additional dangers. Imagine a search feature that looks through the inventory in some potentially CPU-heavy way. I want to limit how many times this code executes before giving up, but I don’t want to hard-code the number and forget it exists, or have to open the code to find out. Still, I don’t want anyone to change it without know exactly what they’re doing. This forces future-me to go into the code to change the value, but I won’t forget it exists.