如何阻止Unity捕获并忽略所有异常,实现调试自动中断?
解决Unity捕获异常/断言后不中断调试的问题
1. 替换Unity内置断言为自定义断言
Unity的Debug.Assert仅打印日志不会中断程序,你可以自行实现断言逻辑,在断言失败时主动触发调试中断:
using UnityEngine; public static class MyDebug { [System.Diagnostics.Conditional("UNITY_EDITOR")] public static void Assert(bool condition, string message = "Assertion failed!") { if (!condition) { Debug.LogError(message); // 触发编辑器调试中断 Debug.Break(); // 抛出异常保留完整调用栈 throw new System.AssertionException(message, null); } } }
使用时直接替换Debug.Assert为MyDebug.Assert,编辑器模式下断言失败会立刻中断,同时保留完整调用栈与变量信息。
2. 自定义全局异常处理(仅编辑器模式)
注册全局异常监听,拦截未处理异常并主动中断调试,同时过滤Unity内部无关异常:
using UnityEngine; using UnityEditor; [InitializeOnLoad] public static class EditorExceptionHandler { static EditorExceptionHandler() { AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; } private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { var exception = e.ExceptionObject as System.Exception; // 过滤Unity引擎/编辑器内部抛出的异常 if (exception != null && !exception.Source.StartsWith("UnityEngine") && !exception.Source.StartsWith("UnityEditor")) { Debug.LogError($"未处理异常: {exception.Message}\n{exception.StackTrace}"); Debug.Break(); } } }
该脚本会在编辑器启动时自动注册,仅拦截业务代码抛出的异常,避免被Unity内部异常干扰。
3. 优化Visual Studio异常设置
针对你已尝试的VS异常设置,可进一步精准过滤:
- 打开「Debug -> Windows -> Exception Settings」
- 展开「Common Language Runtime Exceptions」,取消所有默认勾选项
- 手动勾选你业务代码中会抛出的异常类型(如
NullReferenceException、自定义异常类) - 或右键目标异常类型,选择「Edit Conditions」,添加过滤规则(例如仅当异常
Source为你的项目命名空间时触发中断)
设置完成后,仅你关心的异常会触发调试中断,Unity内部异常将被忽略。
4. 调整Unity编辑器错误处理配置
在Unity编辑器中:
- 打开「Edit -> Project Settings -> Player -> Other Settings -> Configuration」
- 将「Error Handling」设置为
Explicitly Thrown Exceptions Only - 确保「Script Debugging Enabled」处于勾选状态
此设置会让Unity仅处理你显式抛出的异常,减少内部异常的干扰。
内容的提问来源于stack exchange,提问作者Guanyuming He
相关产品推荐
相关产品推荐

