MonoBehaviour execution order from Edit to Play mode and back.

How do I check the execution order of MonoBehaviour-derived event functions/methods in the context of switching back and forth from Edit to Play mode and back?

The execution order of event functions in a monobehaviour-derived class is mostly detailed here. Also relevant is this page on execution order settings.

But more to the point, a simple script will allow you to track execution order through the console:

using UnityEngine;

[ExecuteInEditMode]
public class ExecutionOrderDisplay : MonoBehaviour 
{
	private string id;
	
	private string checkMode()
	{
		if(Application.isPlaying)
			return "PlayMode";
		else
			return "EditMode";
	}
	
	void Awake() 
	{
		id = GetInstanceID() + "";
		
		Debug.Log(checkMode()+"::ExecutionOrderDisplay::"+id+"::"+name+"::Awake()");	
	}
	
	void OnEnable()
	{
		Debug.Log(checkMode()+"::ExecutionOrderDisplay::"+id+"::"+name+"::OnEnable()");
	}
	
	void Start() 
	{
		Debug.Log(checkMode()+"::ExecutionOrderDisplay::"+id+"::"+name+"::Start()");
	}
	
	void Update() 
	{
		// enabling the next line clogs the console, obviously
		// Debug.Log(checkMode()+"::ExecutionOrderDisplay::"+id+"::"+name+"::Update()");
	}
	
	void OnDisable()
	{
		Debug.Log(checkMode()+"::ExecutionOrderDisplay::"+id+"::"+name+"::OnDisable()");
	}
	
	void OnDestroy()
	{
		Debug.Log(checkMode()+"::ExecutionOrderDisplay::"+id+"::"+name+"::OnDestroy()");
	}
}

Crucially, note the [ExecuteInEditMode] directive, as it is what allows the script to function in both Edit and Play modes. To use the script, simply drag&drop it on an object’s components list. In the case of a simple, default cube, it will result in something like this:

On Drag&Drop:

  • EditMode: Awake()
  • EditMode: OnEnable()
  • EditMode: Start()

On Switching to Play Mode:

  • EditMode: OnDisable()
  • EditMode: OnEnable()
  • EditMode: OnDisable()
  • EditMode: OnDestroy()
  • PlayMode: Awake()
  • PlayMode: OnEnable()
  • PlayMode: Start()

On Switching back to Edit Mode:

  • PlayMode: OnDisable()
  • PlayMode: OnDestroy()
  • EditMode: Awake()
  • EditMode: OnEnable()
  • EditMode: Start()

Somewhat interestingly, and maddeningly, is the OnEnable()/OnDisable pair after the first OnDisable() while switching from Edit Mode to Play mode. That’s where most of the trouble occurs while trying to come up with custom serialization/file writing functionality. It’s unclear why Unity must call that pair instead of simply OnDisable(), OnDestroy() and then entering Play mode. Perhaps is a recompilation step and re-enabling the script catches potential errors? Only speculation at this point as I am not aware of specific documentation on the matter.

Please check official documentation.