Just for curiosity: why OnValidate is called twice when “play” is pressed in the editor?
public class OnValidateTest: MonoBehaviour
{
void Awake()
{
Debug.Log("Awake called");
}
void OnValidate()
{
Debug.Log("OnValidate called");
}
}
When I give this script to a single game object and press “play” in the editor, the log looks like this:
OnValidate called
OnValidate called
Awake called
So what I understood from this is that Unity is still in “Editor mode” when it loads scripts for the game, but I don’t understand why OnValidate is called twice? Also I haven’t tried if this happens also in a builds, but my wild guess is it doesn’t since (I suppose) there is no “Editor mode” in builds. This also rises other question: would this in some cases lead to a situation, where the game works fine in the editor but crashes in build?
This is totally true, but when you are in Unity editor, changes in inspector or in script it will call automatically.
If you build the game it wont call the OnValidate function.
See the documentation
1 Like
Yeah, I know this already. What I really want to know is what is exactly happening when “play”-button in the editor is pressed. One of the “OnValidate called” -logs comes when the script is loaded, but how about the other?
Also I’d like to hear if there is some motivation to keep Unity in the Editor mode when “play” is pressed and why this decision is made by the developers of Unity.
I have found OnValidate handy in handling children of a game object. Like if the script has a list of values which determines what kinds of children the game object has and I want to have access to those children in the editor for reason or another, I react to changes in OnValidate. This all works fine until I press “play” - for some reason it sometimes breaks the whole thing. If I comment OnValidate before I press “play”, no problem. So the double call somehow breaks the system.
I know I could use custom editors for this kind of stuff, but this limitation feels a bit artificial and the children of the game object are mandatory properties of the game object, so I see no reason to separate this functionality out of the script itself. So far I’ve solved all of the major problems that the double call causes, but it is just a guesswork before I really know what is happening when the “play”-button is pressed.
2 Likes