0
0
Unityframework~5 mins

Public vs SerializeField in Unity

Choose your learning style9 modes available
Introduction

We use public and [SerializeField] to control how variables show up and can be changed in Unity's Inspector. This helps us organize and protect our game data.

When you want a variable to be visible and editable in the Inspector for easy tweaking.
When you want to keep a variable private but still want to set it in the Inspector.
When you want other scripts to access or change a variable directly.
When you want to hide a variable from other scripts but still save its value in the Inspector.
Syntax
Unity
public int myNumber;
[SerializeField] private int myNumber;

public makes the variable visible to all scripts and the Inspector.

[SerializeField] makes a private variable visible in the Inspector but hidden from other scripts.

Examples
This variable is open to all scripts and shows in the Inspector.
Unity
public int score;
// score is visible and can be changed by other scripts and in Inspector
This variable is hidden from other scripts but you can still set it in the Inspector.
Unity
[SerializeField] private int health;
// health is private but visible and editable in Inspector
This variable is private and not shown in the Inspector.
Unity
private int speed;
// speed is hidden from Inspector and other scripts
Sample Program

This script shows three variables with different visibility. You can see and change publicScore and privateHealth in the Inspector. hiddenSpeed is hidden. The Start method prints their values.

Unity
using UnityEngine;

public class Player : MonoBehaviour
{
    public int publicScore = 10; // visible to all and Inspector
    [SerializeField] private int privateHealth = 100; // private but visible in Inspector
    private int hiddenSpeed = 5; // private and hidden in Inspector

    void Start()
    {
        Debug.Log($"Public Score: {publicScore}");
        Debug.Log($"Private Health: {privateHealth}");
        Debug.Log($"Hidden Speed: {hiddenSpeed}");
    }
}
OutputSuccess
Important Notes

Use public only when you want other scripts to access the variable.

[SerializeField] is great for keeping variables private but still editable in the Inspector.

Keeping variables private helps protect your data and avoid accidental changes from other scripts.

Summary

public variables are visible to all scripts and the Inspector.

[SerializeField] makes private variables visible in the Inspector only.

Use private with [SerializeField] to keep data safe but editable in Unity Editor.