0
\$\begingroup\$

I'm coming from Unreal, and in Unreal you can use the constructor to make logic that is called in editor (as well as when beginning play). This is useful for some things, but Unity documentation says that you shouldn't try to use the constructor of a MonoBehaviour.

I used to think Awake() was called in editor, but it isn't, it's called before Start() but only in play mode.

So, is there some other Method that is called in editor AND in game?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Do you want to call the method manually or automatically? You can take a look at docs.unity3d.com/ScriptReference/ExecuteInEditMode.html as well if this is what you want \$\endgroup\$
    – Zibelas
    Commented Jun 5, 2023 at 18:53
  • \$\begingroup\$ @Zibelas I think an answer explaining how to use ExecuteInEditMode for this purpose would be a good addition to this Q&A thread. \$\endgroup\$
    – DMGregory
    Commented Jun 5, 2023 at 23:50

1 Answer 1

3
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Calling a method from both OnValidate() and Awake() seems like a good idea! I'll try that, thanks! \$\endgroup\$ Commented Jun 6, 2023 at 13:32
  • \$\begingroup\$ @AlexandreMarcati Yes Awake() + OnValidate() combo can be useful to initialize in edit mode aswell as play mode (when created and if inspector change is made). \$\endgroup\$
    – Nikaas
    Commented Jun 10, 2023 at 9:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .