In Unity, the [SerializeField]
attribute is used to make private fields visible and editable in the Inspector window of the Unity Editor. This allows developers to keep variables encapsulated (i.e., not publicly accessible in code) while still customizing them in the Editor.
🧠 Why Use [SerializeField]
?
- Encapsulation: Keeps your variables
private
(good coding practice). - Editor Access: Still lets you assign and tweak values in the Unity Inspector.
- Cleaner API: Prevents public access from other scripts, reducing unintended changes.
🆚 Compare With public
:
Approach | Visible in Inspector | Accessible from other scripts |
---|---|---|
public | ✅ Yes | ✅ Yes |
private | ❌ No | ❌ No |
[SerializeField] private | ✅ Yes | ❌ No |
🧪 Code Example:
Using the practice code from Unity in Practice 0007 – Very First Unity C# Code to Move and Jump a 2D Ball – Wonderful Code See as an example:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallScript : MonoBehaviour
{
private Rigidbody2D rb;
// refactor previous public properties to private via [SerializeField]
[SerializeField] private float moveSpeed;
[SerializeField] private float jumpForce;
private float xInput;
// Start is called before the first frame update
void Start()
{
// refactor: keep rb private and no need inspector access via [SerializeField]
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
// Get horizontal input
xInput = Input.GetAxis("Horizontal");
// Apply horizontal movement
rb.velocity = new Vector2(xInput * moveSpeed, rb.velocity.y);
// Jump on Space key press
if (Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
}
}