Use of SerializeField

From the docs (https://docs.unity3d.com/ScriptReference/SerializeField.html) it looks like SerializeField annotation is used to expose the annotated field to the inspector when it is marked as private visibility. You could do the same obviously with public fields (which we’ve been using up until this point).

What are the reasons for using one over the other?

Serialized fields are still PRIVATE fields that can be edited and saved in the editor. Public fields, while doing the same thing, are still public and using public fields too much breaks the concept of encapsulation.

Essentially, you don’t want to allow scripts outside the one you declare a field in to have access to that field unless you SPECIFICALLY designed it that way. This prevents accidents in complex code. If you use a public field solely for the purpose of having access to it in the editor, every other script could get access to that field and change it. If you make is serialized, it can not be access outside of that script because it is still a private field.

In short, use serialized fields if you want a PRIVATE field, that can be changed in the editor.
Use Public only if you want to access that field on other scripts.

If you want to SEE what a field is during game time (to verify values for example), but you don’t need to edit it at all in the editor, you can toggle debug mode and this will show every field in the script and it’s values. I say this because I have seen people make a field public simply so they could “watch” what is was doing. But again you opened up that field to be manipulated outside it’s scope.

Hope this helps.
Here is a script from my project based on the Unity 2.0 course .
Every single one of these fields, even the particle ones, are serialized fields, with the exception of:
Get Health and Get Shield, which are public so that another script can access those values when needed.

With this setup, I can change, health, shields, and any number of things in the editor for the purpose of testing and fine tuning numbers, but another script has ZERO access to those and some other programmer (if you are on a team) can’t accidentally go in and change stuff not realizing it in a script he is working on. In truth I should have set Get Health and Get Shield to [HideInInspector] since I want other scripts to use it, but don’t need to see it in the inspector (hide in inspector makes it public but does not show it in the editor)

On a side note: If you ask the Unity community, they say ignore the Unity Docs about serialized fields. It says they are hardly used, everyone else says use them instead of public always.

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms