50 Unity Tips #16: OnValidate
Unity UnityTipsTricksYesterday we talked about the [Range] attribute which ensures that float/int values entered in the inspector are constrained to a certain range, thus ensuring valid input. However wouldn’t it be great to validate data for all properties, not just those of type float and int?
OnValidate is a callback when a script extending MonoBehaviour or ScriptableObject (not mentioned in the API) is loaded or the value of a property is changed in the inspector. Here we can use if statements or assertions to check that the inputted data is valid.
public class MyComponent : MonoBehaviour
{
[SerializeField] private Button myButton;
private void OnValidate()
{
Assert.IsNotNull(myButton, "Expected myButton to be not null");
}
}
Further Reading
Scripting API - MonoBehaviour.OnValidate()
Scripting API - Assertions.Assert
This post was generated from a GitHub repository.