There is a third option, instead of using
[SerializeField] private type _myField;
you can use
[field: SerializeField] public type myField {get; private set;}
You gain the option to add a public getter, while keeping the setter private and exposed in the inspector. However, it seems to break the [Header()] tags within unity.
I find it useful for some (certainly not all though) use cases
This is good to know! Thank you for sharing!
Yup that’s a valid option if you want that field to be read by other classes
yes unfortunately, Unity doesn’t show auto-properties yet
I’ve almost always taken a page out of the C++ book in this instance and would have a
private int exampleVariable
public int ExampleVariable { get { return exampleVariable; } }
This way we keep the main instance private and un-editable from other scripts but are still able to access it.
Yes, that is always a valid way to get the best of both worlds. You can even shorten it a bit to
[SerializeField] private int _i;
public int I => _i;
What do you mean it breaks the header tags? I haven’t been able to see any difference so far between that and serialized field
Unity can serialize auto properties to Inspector with [field: SerializeField] attribute.
[field: SerializeField] for auto properties does not break Header attribute, you must simply add the same target specifier to other attributes including the Header and it’ll work.
[field: Header("HeaderName")]
[field: SerializeField] public T Variable { get; private set; }