Search code examples
c#unity-game-engineserializationproperties

Property not displaying in inspector, even with [field: SerializeField]


I've started using [field: SerializeField] to serialize properties so they show up in the inspector, like so:

[field: SerializeField] public int foo { get; private set; }

However, when I add functionality to the the property, it stops working.

private int _bar;

[field: SerializeField] 
public int bar
{
     get { return _bar; }
     set 
     { 
          _bar = value;
          DoThing();
     }
}

The keyword field has a green underline with the following warning:

"field" is not a valid attribute location for this declaration. 
Valid attribute locations for this declaration are 'property'. 
All attributes in this block will be ignored.

This seems to be disabling the attribute altogether, meaning it doesn't show up in the inspector.

I've tried replacing it with [property: SerializeField] like it suggests, but this doesn't show up in the inspector, nor can I find anything about it online.

I'm aware that I can create a custom inspector that will display it, but it's a lot of extra effort for what I'm trying to do, and I want to avoid it if possible.

Is there a way to get a property like this to display in the inspector without a custom editor?


Solution

  • You can't serialize properties in Unity.

    Serialize your backing field "_bar" instead. Or write a custom editor for that object type if you want more control in the inspector.