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.
Public vs SerializeField in 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.
public int score; // score is visible and can be changed by other scripts and in Inspector
[SerializeField] private int health; // health is private but visible and editable in Inspector
private int speed; // speed is hidden from Inspector and other scripts
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.
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}"); } }
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.
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.