I need to validate some data!

Everybody knows that most of editor scripts you created, will be used by people like level designers and game designers. It’s always a good idea to put extra checking to what data they enter while building the scene. They shouldn’t care about values limitations but you have to! ūüėČ

I found a OnValidate function as one of the best ways to validate input data.

How to use OnValidate?

There is only a short description on unity site about OnValidate function and no examples.

In the nutshell – OnValidate function is called in editor mode only on the following cases:

  • once script loaded;
  • if any value is¬†changed in inspector.

Here’s how to use it in the script:

This will produce the following behavior:

OnValidate simple behavior

Examples

Here is some real life examples that displays the power of¬†OnValidate¬†function ūüôā

Degree simplification

Use case – I need to simplify input degree value to range from -359 to 359, because 360 is the same to 0

Implementation

I’m using modulo operator here to get reminder after divide to 360. Check more information about modulo at dotnetperls

Result

OnValidate - Degree simplification

Power of two

Use case РI need to have power of two values from 16 to 4096

Implementation

Unity has a handy ClosestPowerOfTwo method that ideally fits our needs.

Also I use RangeAttribute here to limit input values and it looks more friendly comparing to default input field.

Result

OnValidate - Power of two

Linked values

Use case¬†–¬†I need to have car “Nitro” speed to be greater than regular car speed at least to 20mph

Implementation

Comparing to previous examples I use extra tag here TooltipAttribute to display hover tooltip in inspector

Result

OnValidate - Linked values

PS (This is something I’ve learned while creating UI tools plugin for Unity and other projects)