Use Debug.Break() to pause Unity editor from the code

You can pause your game from the editor any time you want. But did you know that you can trigger the pause from the code based on some condition?

error pause console

There’s a console option called Error Pause. When enabled, it will pause your game when any run-time error occurs. When your game is paused, you can easily investigate what is going on your scene so you can better understand the problem. But what if you want to pause your game on a custom condition? It can also be done!

In order to do this, you have to use the Debug.Break() function. Just call it when you want to pause your Unity editor.

Example

using UnityEngine;

public class DebugBreakExample : MonoBehaviour {
	void OnGUI() {
	    if (GUILayout.Button("Pause Now!")) {
	        Debug.Break();
	    }
	}
}

This example displays a button in the top-left corner. When the button is clicked, the editor pauses.

Debug.Break() has one more significant advantage over manual pausing and stepping forward. It can pause your game in the middle of an execution frame. This means that part of your object may be still waiting for the Update() call and the other part has already been updated. This is really useful for situations when you’re dealing with a bug that appears randomly.

Don’t worry about leaving Debug.Break() functions in your code. When your game is built it literally does nothing! 🙂

Files

As usual, you can download the example unitypackage here. Just double-click on it to import its contents into your Unity project. You will find there an example scene and the script from above.

related
IntermediateMultiplayerTutorial
Building a Turn-Based Multiplayer Game with GameSparks and Unity: Part 3
Welcome to the third part of our GameSparks tutorial series. In parts one and two we have finished...
0
IntermediateTips
A Story of NullReferenceException [Part 1]
Once upon a time there was a little boy living with his mother alone between the mountains....
2
AdvancedTipsTutorial
Understanding the Importance of Using Multiple Cameras in Unity
From what I observe, many Unity users do not grasp the concept of using multiple Unity cameras...
7
Call The Knights!
We are here for you.
Please contact us with regards to a Unity project below.



The Knights appreciate your decision!
Expect the first news soon!
hire us!