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:
1 2 3 4 5 6 7 8 9 10 |
using UnityEngine; using System.Collections; public class OnValidateExample : MonoBehaviour { public int size; void OnValidate() { Debug.Log("OnValidate"); } } |
This will produce the following 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
1 2 3 4 5 6 7 8 9 10 11 |
using UnityEngine; using System.Collections; public class OnValidateExample : MonoBehaviour { public float objectRotation; void OnValidate() { // objectRotation objectRotation = objectRotation % 360; } } |
Result
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
using UnityEngine; using System.Collections; public class OnValidateExample : MonoBehaviour { [RangeAttribute(16, 4096)] public int textureSize; void OnValidate() { // textureSize textureSize = Mathf.ClosestPowerOfTwo(textureSize); } } |
Result
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using UnityEngine; using System.Collections; public class OnValidateExample : MonoBehaviour { [RangeAttribute(10, 300)] [Tooltip("mph")] public int maxCarSpeed; [RangeAttribute(10, 300)] [Tooltip("mph")] public int maxNitroSpeed; const int minNitroSpeedExtra = 20; void OnValidate() { // speed check if (maxNitroSpeed < maxCarSpeed + minNitroSpeedExtra) maxNitroSpeed = maxCarSpeed + minNitroSpeedExtra; } } |
Result
PS (This is something I’ve learned while creating UI tools plugin for Unity and other projects)