[NonSerialized] vs [HideInInspector] question

Hi! What does serialization mean? I mean I know what serialization is, but I don’t know what Unity uses it for. I would think that it is for variables to show up or not to shop up in the editor, but for that there is the HideInInspector attribute.
I only would like to know what is the difference between NonSerialized and HideInInspector. :slight_smile:

Thanks in advance.

Each variable can be either shown or hide in the inspector. Each variable can be either saved between sessions, or not. Add to that the normal variable scope private/public.

By default, Unity use the same logic for each variable; private are NonSerialized and HideInInspector; public are SerializeField (and shown in inspector).

  • HideInInspector make sure a variable is not displayed.
  • NonSerialized make sure a variable state is reset to default on game state change.
  • SerializeField make sure a variable value instance has its own default value.

You can add these attributes on both private and public, where it logically applies. I'd add to that to be aware of HideInInspector [SerializeField] public variables, because they could hold value different of what is displayed in the code, and without removing the HideInInspector attribute - and possibly having to check/reset every instance of the code, you'll never know.

EDIT: Create a new script with only the code below, in JS for simplicity, drag it twice(2x) on a GameObject, try each manipulation listed below then hit play and see what happens:

public var myTest:String = "default";

function Start():void
{
    Debug.Log(myTest);
}

  • Hit Play. Both should print "default".
  • In the inspector, change one of them to "anything". One should print "default" the other should print "anything".
  • In the code, add the @HideInInspector attribute. One should print "default" the other should print "anything". None are visible and the code let think both hold the "default" value. This is what I'm warning about.
  • In the code, add the NonSerialized attribute. Both print "default".

The HideInInspector attribute make it invisible in the inspector but still allow each instance of a SerializeField to hold its own default value. NonSerialized force even a public field to reset to the code default value when you enter and leave play mode.

Its all a game of variable scope/default value/inspector visibility.

HideInInspector keeps your variables saved, but removes clutter from the Inspector. I use it all the time, in combination with [SerializeField]. NonSerialized is used for public variables, which are the only ones that are serialized by default. If you don’t need them saved, then NonSerialized is a more appropriate choice than HideInInspector, if only for semantic reasons.