I want to check that some fields are nonempty before any of the Start() functions run.

I tried to put checks in Awake() and Empty() and to quit Unity if they fail:

        Debug.Log("exit from editor");
        UnityEditor.EditorApplication.isPlaying = false;
        Debug.Log("exit from game");

It hits this code but it doesn't actually quit the game. I found that the Quit / isPlaying = false commands only work from Update

  • 1
    \$\begingroup\$ Have you considered using OnValidate to catch these errors before you even run your game? \$\endgroup\$ – DMGregory Sep 22 '19 at 0:08
  • \$\begingroup\$ @DMGregory whoa that might be exactly what I'm looking for ... \$\endgroup\$ – max pleaner Sep 22 '19 at 0:09

Since what you are trying to do is somewhat related to exception handling consider the exception guidelines from Microsoft:

  • Use try/catch blocks around code that can potentially generate an exception and your code can recover from that exception.

  • For conditions that are likely to occur but might trigger an exception, consider handling them in a way that will avoid the exception.

  • When your code cannot recover from an exception, don't catch that exception. Enable methods further up the call stack to recover if possible.

In your case we:

  • Have conditions that are likely to occur (accidental change of inspector values etc)

  • But (and I only asume this) we can't recover and thus wish to quit the app

Instead of implementing logic to quit the game for every MonoBehaviour you could try to process otherwise unhandled exceptions at a higher level, the application root, by notifying the user and then quitting the game. This would then also work for unhandled exceptions originating from other parts of your code.

We can do this in Unity with the Application.logMessageReceived callback. See this on how it works.

As pointed out by DMGregory you can use MonoBehaviour.OnValidate to validate fields before startup.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.