Unity编辑器扩展:一键清空控制台日志
功能概述
通过自定义快捷键组合(Ctrl+C+D)快速清空Unity编辑器控制台日志,提升开发调试效率。本方案具有以下特点:
- 🚀 零性能消耗:仅在按下快捷键时执行
- 🔒 安全可靠:通过官方反射接口实现
- 🛡 版本兼容:支持2017.4及更新版本
- 📦 开箱即用:仅需一个脚本组件
优化后的完整脚本
#if UNITY_EDITOR
using UnityEditor;
#endif
[DisallowMultipleComponent]
[AddComponentMenu("Debug/Clear Console Helper")]
public class ConsoleCleaner : MonoBehaviour
{
[Header("快捷键设置")]
[Tooltip("推荐使用组合键避免误操作")]
[SerializeField] private KeyCode _modifierKey = KeyCode.LeftControl;
[SerializeField] private KeyCode _triggerKey1 = KeyCode.C;
[SerializeField] private KeyCode _triggerKey2 = KeyCode.D;
#if UNITY_EDITOR
private void Update()
{
if (EditorApplication.isPlaying)
{
if (Input.GetKey(_modifierKey)
&& Input.GetKeyDown(_triggerKey1 )
&& Input.GetKeyDown(_triggerKey2 ))
{
ClearConsoleLogs();
}
}
}
/// <summary>
/// 安全清空控制台日志的方法
/// </summary>
private void ClearConsoleLogs()
{
try
{
var logEntriesType = typeof(EditorWindow).Assembly
.GetType("UnityEditor.LogEntries");
if (logEntriesType != null)
{
var clearMethod = logEntriesType.GetMethod("Clear",
System.Reflection.BindingFlags.Static |
System.Reflection.BindingFlags.Public);
clearMethod?.Invoke(null, null);
Debug.Log("<color=green>控制台日志已成功清空</color>");
}
}
catch (System.Exception e)
{
Debug.LogError($"清空日志失败: {e.Message}");
}
}
private void OnDisable()
{
// 确保退出时恢复控制台状态
ClearConsoleLogs();
}
#endif
}
实现原理
技术架构
关键特性
-
双重安全校验:
- 预处理指令
#if UNITY_EDITOR - 运行时状态检查
EditorApplication.isPlaying
- 预处理指令
-
智能错误处理:
- 空引用检查
- try-catch异常捕获
- 可视化错误反馈
-
灵活配置:
- 可自定义快捷键组合
- 组件自动菜单项
- 禁止重复组件
这个脚本展示了如何在Unity编辑器中通过按下D和C键组合来清空控制台。它利用了System.Reflection来调用UnityEditor的内部方法`Clear`,此功能仅在开发环境中生效,发布时不会执行。
720

被折叠的 条评论
为什么被折叠?



