Unity Tip: Don’t Use Public to Show Fields in the Unity Editor

If you want to see a variable appear in the Unity editor, you don’t need to make it public. You can use [SerializeField] / @SerializeField to do this and keep your variable private.

//UnityScript
@SerializeField
private var _myPrivateString = "You can see this in the Unity Editor";
//C#
[SerializeField]
private string _myPrivateString = "You can also see this in the Unity Editor";

SerializeField is also important if you’re encapsulating properties in scripts… Properties don’t appear in the Unity editor by default, but if you’re using custom editors, you’ll soon slip on this problem…

//C#
private bool _hiddenValueA = false;
[SerializeField]
private bool _hiddenValueB = false;

//_hiddenValueA IS NOT serialised so when you press play it resets!
public bool valueA
{
    get{return _hiddenValueA;}
    set{_hiddenValueA = value;}
}

//_hiddenValueB IS serialised so when you press play it is saved.
public bool valueB
{
    get{return _hiddenValueB;}
    set{_hiddenValueB = value;}
}