Why should I use SerializeField?

Why and when should I use [SerializeField]?

Using the SerializeField attribute causes Unity to serialize any private variable. This doesn’t apply to static variables and properties in C#.

You use the SerializeField attribute when you need your variable to be private but also want it to show up in the Editor.

For example, this wouldn’t show up in the Editor:

private float score;

And this is because it’s a private variable but the one below should show up in the Editor:

[SerializeField]
private float score;

That’s because you applied SerializeField to it and you’re telling Unity to serialize it and show it in the Editor.


Note that private variables has more to do with C# than Unity. There is also public variable variables. Marking your variable private means that you don’t want another script to be able to access that variable. There is also public qualifier. Marking your variable public means that you want your other scripts to be able to access that variable.

Sometimes, you want other scripts to be able to access your variable from another script but you don’t want the public variable to show up in the Editor. You can hide the public variable with the [HideInInspector] attribute.

This will show in the Editor:

public float score;

This will not show in the Editor:

[HideInInspector]
public float score;

Is it bad to leave variables hard coded despite using [SerializeField] and have more text boxes in my unity interface?

Yes, it’s mostly bad especially for new users. It shouldn’t be a big deal for a long time Unity and C# programmer. The reason this is bad is because when you have the code below:

[SerializeField]
private float score = 5f;

The default value is 5 in the Editor. Once you save the script this variable is now updated in the Editor as 5. The problem is that you can change this from the Editor to 14. Once you change it from the Editor, the value in the script will still be 5 but when you run it, Unity will use the value you set in the Editor which is 14. This can cause you so much time troubleshooting something that isn’t even a problem just because there is a different value being used that is set in the Editor while you’re expecting the default value set in the script to be used.

The only way for for the score variable to reset back to it’s default 5 variable is when you either rename the variable to something else or reset it from the Editor. It won’t even change even when you change the value from 5 to 3 from the script. It has to be renamed or reset from the Editor. It’s worth knowing but when you get used to Unity, you won’t have to worry about this.

Leave a Comment