OnValidate()
Editor-only function that Unity calls when the script is loaded or a value changes in the Inspector.
Read time 1 minuteLast updated 3 days ago
Definition
- Type: Method
- Namespace: UnityEngine
public void OnValidate()
Remarks
Use this to perform an action after a value changes in the Inspector; for example, making sure that data stays within a certain range.
OnValidateOnValidateOnValidateYou can't reliably perform Camera rendering operations from . Instead, add a listener to EditorApplication.update, and perform the rendering during the next Editor Update call.
OnValidateAdditional Resources: EditorApplication.update, EditorApplication.delayCall.
Examples
using UnityEngine;public class Health : MonoBehaviour{ [SerializeField] private int maxHealth = 100; [SerializeField] private int currentHealth = 100; // Called in editor when values are changed in Inspector private void OnValidate() { // Ensure maxHealth is at least 1 if (maxHealth < 1) maxHealth = 1; // Clamp currentHealth between 0 and maxHealth currentHealth = Mathf.Clamp(currentHealth, 0, maxHealth); }}