- Home /
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..)
Answer by incorrect · Feb 12, 2015 at 03:30 AM
I've found one way. :)
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;
[ExecuteInEditMode]
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))
{
sw.WriteLine(System.DateTime.Now.ToString());
}
}
}
}
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.
Of course you can write to the file the opening session's id and closing session's id, and if they do not match you will know that last time editor has crashed. It's not hard to make it.
Answer by farrisarts · Feb 12, 2015 at 03:04 AM
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.