How do variables and the Inspector work in Unity scripts?

← Unity answers

Public fields, and private fields marked [SerializeField], appear in the Inspector, where you can edit them per object. The Inspector value overrides the initial value written in code.

using UnityEngine;
 
public class Player : MonoBehaviour
{
    [Header("Movement")]
    public float speed = 5f;                       // visible, editable from other scripts too
 
    [SerializeField] private int health = 100;     // visible, but private to the class
 
    [Range(0f, 1f)] public float volume = 0.5f;    // slider in the Inspector
 
    [HideInInspector] public bool isDead;          // public but hidden
 
    private Rigidbody body;                        // not serialized
 
    void Awake() => body = GetComponent<Rigidbody>();
}
  • Serialized fields are saved with the scene or prefab, so changing the default in code does not change objects that already exist; use Reset in the component menu.
  • Values changed during Play mode are lost when you stop.
  • Prefer [SerializeField] private over public to keep other scripts from modifying a value by accident.
  • Fields set to static, const or readonly are not shown.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required