'C# Compilation Error on Header For Shorthand Class property

I am trying to put a Header before a field which utilizes getter + setter shorthand syntax but I am getting a compile time error saying "Attribute 'Header' is not valid on this declaration type. It is only valid on 'field' declarations."

Apparently it is no longer considered a field after putting the {get;set;} If I remove the shorthand syntax it works but ideally I want it to stay there. Is there a way to make this work?

The line involved is line 4 with the moveSpeed field.

public class PlayerController : MonoBehaviour
{
    [Header("Movement")]
    [SerializeField] private float moveSpeed { get; set; } = 2.0f;
    [SerializeField] private float jumpForce = 250f;
}

I am using Visual Studio 2019



Solution 1:[1]

Assuming you're working with a relatively modern version of C# (7.3 or later1), you can specify the field target for the attribute:

public class PlayerController : MonoBehaviour
{
    [field:Header("Movement")]
    [field:SerializeField] private float moveSpeed { get; set; } = 2.0f;
    [field:SerializeField] private float jumpForce = 250f;
}

This was specifically added to allow you to target attributes at auto-generated fields.


If you're not working with such a version of C#, then unfortunately, no, you cannot combine auto-implemented properties with attributes that must be placed on the field, and must continue to manually implement such properties.


1 With Unity, I believe that the language version may not always track the latest version supported by Visual Studio, but it looks like every version of Unity back to at least 2018.3 targets C# language version 7.3 or later.

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