Unity3d and public class members

A nice feature of Unity3d IDE is that any public variable in class derived from MonoBehaviour will show in properties editor and can be edited from there, it even picks possible values for enums and resources. Unfortunately, this sometimes leads to undesired effect – as soon as property is changed from IDE, changing it inside source code will not change it’s value. Yip, you write “public int i = 1”, but it will be 0 if you set it to 0 in inspector, because it’s getting serialized to scene data and loaded back on component init. This is quite confusing because there is no way to see if variable is serialized rather than run code and there is no way to unlock/reset variable – only set it to other value.

Special attribute [HideInInspector] can be used to hide variables from editor, but this will not reset it’s value. So if you’ve ever set value from inspector and then add HideInInspector it will be still locked to value from inspector. A correct solution is to use [System.NonSerialized] attribute which will completely exclude variable from list of serialized entries.

Btw, I am not surprised that Unity scripting reference page of HideInInspector is incorrect(C# example missing [HideInInspector]).



Leave a comment