Serialize properties in Unity easily. This wasn’t possible until about a year ago and I think has quietly slipped under the radar! At least I was extremely surprised to find this nugget. You may hear advice to make anything public into a property. And also, to use the property in the script and not the backing field.
This makes the backing field pointless in many ways. And now you can cut the clutter and the busy work by adding a simple target with your attributes on properties to tell Unity to target the backing field.
This cut my variable & property from 6-7 lines down to 2-3. Using auto properties originally would of course save over those 8 lines. But then you wouldn’t have been able to add the attributes.
Old:
[Tooltip("Works with FPS threshold to limit frames that can wait.")]
[SerializeField, Range(0, 200)]
private int _MaxFramesToWait = 10;
public int MaxFramesToWait {
get { return _MaxFramesToWait; }
set { _MaxFramesToWait = value; }
}
I chose this example because it uses serveral attributes, it has an initialized value, and importantly it has the [SerializeField] attribute to show in the inspector in Unity.
New:
[field: SerializeField, Range(0, 200),
Tooltip("Frames. Works with FPS threshold to limit frames that can wait.")]
public int MaxFramesToWait { get; set; } = 10;
Now down to 2-3 lines. You can add attributes to a property by adding the “field:” target.
One rule I’ve found is that Unity requires you to include a set keyword no matter what, either private or not. I combined all the attributes because you would be required to write “field:” in each.
This tells Unity to target the backing field that is created by the compiler, or that’s the idea, since all the documentation and forum search results show that this is still not possible. But like I said, this has been around for about a year and my testing hasn’t shown any short-comings.
If you aren’t familiar with the initializer on the property ( …{ get; set; } = 10 ) it can be used to initialize new things like lists as well. Overall I think this has everything I need to make it my go-to method of writing out properties.
On a related note, I have tried using [SerializeReference] attribute for other uses and have not had good reliable results.