Skip to content

Compare similar Unity attributes

↑
Decision guide

These attributes can look similar while solving very different problems. Start by asking whether you need to change saved data, its Inspector presentation, or when code runs.

Use SerializeField for a normal Unity-supported field. Choose SerializeReference for managed object graphs that need polymorphism, reference identity or cycles. Do not use it for UnityEngine.Object references.

HideInInspector hides a serialized field from the default Inspector. [System.NonSerialized] opts a public field out of Unity serialization. Hiding is not a security boundary.

ExecuteAlways is the recommended modern choice for scripts designed to handle both Edit mode and Prefab Mode. ExecuteInEditMode is legacy and can cause Prefab Mode problems. Neither means disabled MonoBehaviours run as usual.

Put ContextMenu on an instance method to add a command to the component menu. Put ContextMenuItem on a field to add a context-menu action for that field; it is not a persistent Inspector button.

[RuntimeInitializeOnLoadMethod] vs [InitializeOnLoadMethod]

Section titled “[RuntimeInitializeOnLoadMethod] vs [InitializeOnLoadMethod]”

Use RuntimeInitializeOnLoadMethod for runtime startup, including player builds. Use InitializeOnLoadMethod for Unity Editor initialization only, inside an editor-only assembly.

Unity C# | PlayerStats.cs
using UnityEngine;
using UnityEngine.Serialization;
public sealed class PlayerStats : MonoBehaviour
{
[FormerlySerializedAs("startingLives")]
[SerializeField, Min(0)]
private int lives = 3;
public int Lives => lives;
}

FormerlySerializedAs helps Unity read existing Inspector data from the previous field name. SerializeField keeps the field serialized, and Min affects editing in the Inspector.