SerializeField in Unity: Everything You Need to Know
.avif?height=300)
Introduction
In this article, I will explain everything you need to know about the SerializeField attribute in Unity.
By the end of this article, you will know what the SerializeField attribute does.
You will understand what types of fields are serializable. You will feel comfortable deciding when and where to use it in your code.
You will also learn about [System.NonSerialized] and [field:SerializeField] attributes.
Key Takeaways for SerializeField
- Use private fields and variables in your classes.
- If you want Unity to show a field in the Inspector, use the SerializeField attribute,
[SerializeField]. - You use the SerializeField attribute like this:
[SerializeField] private int MaximumHealth;
What does SerializeField do?
SerializeField forces Unity to serialize a field.
If you understand what Serialization means, understanding SerializeField is easy.
Do you want to see and edit private values but don’t want the values saved?
So when you edit it, the changed value vanishes into the ether?
Why is it essential that the values not be serialized to disk?
And if that is important, what is the point of editing them if they disappear?
- Unity wants to draw all the fields in the class in the Inspector.
- But, it can only draw fields that are serialized on the disk.
- When you serialize the field, Unity has a copy on the disk that it can use to draw the field in the Inspector.
- When you change the value in the Inspector, you are changing the serialized object.
- Therefore, you must use SerializeField to enable Unity to draw an editable field in the Inspector.
In the next section, I’ll explain what Serialization means in Unity, offer an analogy, and a couple of examples.
What does Serialization mean in Unity?
In this section, I’ll explain what serializing a field in Unity means. I will explain how Serialization impacts your project.
Then, I will give an example of a serialized field, an implicitly serialized field, and a non-serialized field to illustrate how they work differently…
Create a free account, or log in.
Gain access to free articles, game development tools, and game assets.