Skip to content

Conversation

@atcarter714
Copy link

The C# [SerializeField] attribute in Unity is only allowed on fields, not the get/set methods of a property, therefore when serializing the backing field of an auto-property (implicit backing field generated by Roslyn), it is necessary to use the field: specifier to target that generated field:

[SerializeField] public int Counter { get; set; } //! ERROR
[field: SerializeField] public int Counter { get; set; } //! OK

The C# [SerializeField] attribute in Unity is only allowed on fields, not the get/set methods of a property, therefore when serializing the backing field of an auto-property (implicit backing field generated by Roslyn), it is necessary to use the `field:` specifier to target that generated field:

[SerializeField] public int Counter { get; set; } //! ERROR
[field: SerializeField] public int Counter { get; set; } //! OK
@atcarter714
Copy link
Author

atcarter714 commented Nov 26, 2025

[field: SerializeField] is a great way to convert explicit pairs of public/protected backing fields with properties into "auto-property-style" declarations and still be able to serialize in the Unity Editor, but be cautious: some parts of Unity's old editor GUI system doesn't comprehend the syntax during reflection and will behave in odd ways. However, it is great most of the time and encouraged for cleaning up outdated codebases.

You can attach other kinds of attributes (which have the AttributeUsage target flag AttributeTargets.Property) to get/set methods of properties though:

protected int _count ;
public int Counter { //! Aggressive inlining (0x100):
	[MethodImpl(0x100)] get => _count ;
	[MethodImpl(0x100)] set => _count = value ;
}

(And there are of course other specifiers, like return:, method:, etc ...)


EDIT :: Doubled back to delete that dead attribute on line 598 and gave an explanation (has an explicit field already serialized) ...

Line 598 actually needs no `SerializeFieldAttribute` ... I overlooked the explicit field already tagged with it right above it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant