The usefulness of [SerializeField] attribute

Hi guys,

I have to repost my question about [SerializedField]

This is not about saving game preferences (I already used PlayerPrefs). I only trying to understand if the ONLY vantage of using [SerializedField] is to expose a private variable in the Inspector (that is convenient to change values, and at the same time it respects the classes encapsulation principle) or if there is some other convenience in using it.


Yes. But the actual benefit is to be able to make ALL fields private with the OPTION of exposing them in the Inspector as needed. [SerializeField] is the tool that allows you to follow best practices.

Whereas, unfortunately for ease of introduction, Unity script examples and tutorial almost always prefer to make the fields public. Therefore it seems kind of odd having to write even more code to do the same thing. Once you understand the problems public fields cause, you won’t turn back.

Case in point: there was a thread just two days ago that was about some script in the project setting a counter field to zero in another script at some point during the game - and there is simply no way to set a single breakpoint (no breakpoints on fields) to check for that occurance.

Of course that’s not the only concern that make private fields not just a best practice, but THE practice that you only violate purposefully for record structs (“just a bunch of variables” struct) …