Unity Editor: Detect Crash OR Editor Exit?

I know Application.Quit is when the built game is exited, but how would I go about doing this for when the editor is exited? A better option would also be a way to detect if there was a crash previously.

Is it possible?

(Detect editor exit so I can create a log, which won’t work if it crashes…)

Normally you would use try/catch and exeptions however since you are talking about the Editor there is no way to detect a crash. In fact, a crash inherently is handled by the operating system. The only ones that can detect any kind of crash is Unity themselves in their engine code.

So in order to get something like this you can actually do a few things to detect when a crash happens and what you were doing before the crash. The easiest way to do this is to write to a log file stream in which you can open up and read after the crash.

I’ve found one way. :slight_smile:

You can use ExecuteInEditMode attribute to make it, have an instance of a logger in a scene and make it work like this:

using UnityEngine;
using System.Collections;
using System;
using System.IO;

public class TestScript : MonoBehaviour {

	// Use this for initialization
	void Awake () {
		Debug.Log ("It works!");

	void OnDestroy()
		string path = @"C:\Users\**YOUR_PROFILE**\Documents\MyTest.txt";
		// This text is added only once to the file. 
		if (File.Exists(path)) 
			// Create a file to write to. 
			using (StreamWriter sw = File.CreateText(path)) 

This code will write closing time to the MyTest.txt using File.AppendText Method, but you can make anything you want inside OnDestroy(), which will appear every time you close the scene with a logger.