Coding guidelines

First, read the API Introduction about UI and naming conventions!

Fields, done propertly

This is a simple field:

public float Number;

The above code has just a single benefit: it's fast to write. Besides that, it's horrible for a number of good reasons:

  • no input validation
  • setting values might mark your scene dirty though the value hasn't changed
  • no way to react to changes, e.g. refresh something

So, forget the above code. Don't use it! Never! Ever!

Instead, this is the same field (with some input validation added) done the right way:

float m_Number;

public float Number
  get { return m_Number;}
     float v=Mathf.Clamp01(value);
     if (m_Number!=v)

        void OnValidate()
            Number = m_Number;

Heck, that's pretty much code for a simple field. So, why this?

When accessing the field by code the property should be used and you can be sure that input is validated. The serialized field “m_Number” is used by inspectors instead with no input validation, but OnValidate() is called by the editor afterwards, so you can just set the property again to apply input validation and subsequent actions.

Having PropertyDrawers like [Range(0,1)] will add input validation to inspector fields, but then you're missing validation when setting the field from code.

Unity folks do it this way, you should do the same for the above good reasons!


Enter your comment:
Last modified: 2015/09/23 20:14 by Jake