Search code examples
unity-game-engine

Unity OnValidate() does not react


This method is supposed to be called for each change in the inspector. When the script is changed and thus reloaded, the method works perfectly: The position gets snapped and the console reacts. However, the method ignores any further changes in the inspector, for example dragging the game object having the script or changing values manually. What could be missing to make it react to changes?

public void OnValidate()
{
    UpdateCellPosition();
    Debug.Log("works");
}

Solution

  • From the Unity Scripting API:

    Editor-only function that Unity calls when the script is loaded or a value changes in the Inspector.

    OnValidate only ever reacts to changes within the script itself, not for changes to other component (like Transform, in your "moving the object around" example).

    There currently isn't a callback for changes that occur outside of your own script. You could bodge an implementation with [ExecuteAlways] (slow, if you're doing complex things every frame!), or use an event such as EditorSceneManager.sceneSaving to run your OnValidate() manually before the scene saves.