Quantcast
Channel: Answers for "[NonSerialized] vs [HideInInspector] question"
Viewing all articles
Browse latest Browse all 4

Answer by by0log1c

$
0
0

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.


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles



Latest Images