0
0
UnityHow-ToBeginner ยท 3 min read

How to Use SerializeField in Unity: Simple Guide

In Unity, use [SerializeField] before a private field to make it visible and editable in the Inspector without making it public. This helps keep your data private in code while still allowing easy editing in the Unity Editor.
๐Ÿ“

Syntax

The [SerializeField] attribute is placed directly above a private field declaration. It tells Unity to save and show this field in the Inspector even though it is private.

  • [SerializeField]: The attribute that enables serialization.
  • private: Access modifier keeping the field hidden from other scripts.
  • type: The data type of the field (e.g., int, float, string, GameObject).
  • fieldName: The name of the variable.
csharp
using UnityEngine;

public class Example : MonoBehaviour
{
    [SerializeField]
    private int speed = 5;
}
๐Ÿ’ป

Example

This example shows a private integer speed field with [SerializeField]. It appears in the Unity Inspector and can be changed there, but other scripts cannot access it directly.

csharp
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField]
    private float speed = 10f;

    void Update()
    {
        float move = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        transform.Translate(move, 0, 0);
    }
}
Output
When attached to a GameObject, the 'speed' field shows in the Inspector and controls horizontal movement speed.
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Forgetting [SerializeField] on private fields, so they don't show in the Inspector.
  • Making fields public just to see them in the Inspector, which breaks encapsulation.
  • Expecting [SerializeField] to work on local variables (it only works on fields).
csharp
using UnityEngine;

public class WrongExample : MonoBehaviour
{
    private int score = 0; // Won't show in Inspector

    [SerializeField]
    private int health = 100; // Shows in Inspector
}
๐Ÿ“Š

Quick Reference

FeatureDescription
[SerializeField]Makes private fields visible and editable in the Inspector
Private fieldsKeep data hidden from other scripts but editable in Editor
Public fieldsAlways visible in Inspector but accessible by other scripts
Works on fields onlyCannot serialize local variables or properties
Use for encapsulationKeep code clean and safe while allowing easy tuning
โœ…

Key Takeaways

Use [SerializeField] to show private fields in the Unity Inspector without making them public.
This keeps your data safe from other scripts but editable in the Editor.
Do not use [SerializeField] on local variables; it only works on fields.
Avoid making fields public just to see them in the Inspector to maintain good code design.
Use [SerializeField] to balance encapsulation and easy tuning of values.