1

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

Paolo Tormon
  • 312
  • 2
  • 11
  • 1
    Properties should be `PascalCased`, not `camelCased`. Only fields should be `camelCased`. – Dai Mar 30 '22 at 14:05
  • @Dai coming from Java I did not know that in C# there is a difference between properties and fields. Thanks for the clarification, more details can be found here https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property – Paolo Tormon Apr 01 '22 at 04:25

1 Answers1

2

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.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • @Dai - We must be reading "Attribute **'Header'** is not valid on this declaration type. It is only valid on 'field' declarations." differently. – Damien_The_Unbeliever Mar 30 '22 at 14:06
  • Acutally it's both: the docs for `SerializeField` say that, too, is incompatible with properties. – Dai Mar 30 '22 at 14:06