Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Inspector support for auto properties with anonymous backing fields

Discussion in 'Scripting' started by UziMonkey, Jun 7, 2018.

  1. UziMonkey

    UziMonkey

    Joined:
    Nov 7, 2012
    Posts:
    206
    The Unity docs and tutorial usually suggest that you use public fields to get things to show up in the inspector. For reasons I won't go into here this is a real bad idea and I don't do it.

    As a compromise I use [SerializeField] private which works great, but there is some extra typing involved when you want to add a public property to be able to read and/or write this value from outside the script.

    Recent versions of C# support a better solution though: you can put attributes on anonymous backing fields. In other words, you can do [field: SerializeField] public float SomeVar { get; private set; } and all of the requirements are fulfilled in one compact line. The problem is that the backing field that's being serialized has a mangled name. It looks like <SomeVar>k__backing_field and I'm looking for a way to get this to show up as simply SomeVar in the inspector.

    I've tried one thing, implementing a Label attribute that lets me say [field: SerializeField, Label("SomeVar")] public float SomeVar { get; private set; } and this works for some things, but doesn't work for arrays. I don't know enough about the Unity inspector to know if what I want is possible, but if I can get the first form of the this to work (without the Label attribute) to work this would 100% become my new default way of doing inspector fields in Unity.

    I really just don't know how to get started with this stuff, or if it's already there and I'm missing an attribute or if there is an existing asset on the asset store to do this.
     
    phobos2077 likes this.
  2. IgnisIncendio

    IgnisIncendio

    Joined:
    Aug 16, 2017
    Posts:
    223
    I have this same problem too. Also, apparently Unity also now automatically serializes public auto properties? It complains
    The same field name is serialized multiple times in the class or its parent class. This is not supported: Base(WiresModule) <Active>k__BackingField
    when I have an inherited public auto property for example.
     
  3. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,294
    I'm really interested in this - I created a post in the experimental scripting forum, as the relevant devs seem to visit that place more often.