Yes, OnValidate()
gets called only in the Editor (including play mode in-editor) in a few situations:
- When the component is added to a game object
- When a prefab containing the component is instantiated
- When the user changes data in the component's Inspector fields
- When entering play mode
- When reloading the C# assembly containing the
MonoBehaviour
following a code change
- When building the game
Because it can be called repeatedly during the lifetime of a single object, if you want to do any one-time initialization then you'll need to use a flag or some telltale state to check if the object has already been initialized, and skip it if so. If you want the behaviour to be called in both the editor and built executables, you can make a separate Initialize()
method and call it from both OnValidate()
and Awake()
.
Note that OnValidate()
can be called from the loading thread, so it can't be used to perform any tasks that are main-thread-only. What it can do though is set up a listener to invoke the required actions on the main thread after it's run.
There is also Reset()
which is called in-editor when a component is added to an object, before OnValidate()
and when manually resetting a component via its context menu. It's not called repeatedly in the lifetime of a single object outside of this manual intervention, but it also does not get called when instantiating a prefab.