Vrijl
October 22, 2024, 8:26pm
1
I have seen that properties can be provided with the attribute [field: SerializeField] instead of only [SerializeField].
In all the examples I have found, however, a private setter is used:
[field: SerializeField]
public float myVariable { get; private set; }
I’ve just tested it for myself, apparently it also works with a public setter:
[field: SerializeField]
public float defaultHealth { get; set; }
Do I have to pay attention to anything here, or is this fine?
It’s fine. The attribute is being applied to the invisible backing field the compiler is adding, rather than the property itself. Whether the setter is private, protected or public doesn’t make a difference here, as it’s not the property being serialized.
2 Likes
The only “gotcha” that comes to mind is that if you then write a custom Editor or PropertyDrawer you need to target the backing field.
<#>k__BackingField
# = the property name
SerializedProperty myProperty;
void OnEnable
{
myProperty = serializedObject.FindProperty("<MyPropertyName>k__BackingField")
}
2 Likes
Also the same is true if you use the FormerlySerializedAs Attribute later.
2 Likes