# Debug 类

> Use the Debug class in your project code to write messages and errors to the Console window.

Debug 类用于可视化编辑器中的信息，这些信息可以帮助了解或调查项目运行时发生的情况。例如，可以使用该类打印消息至 Console 窗口，在场景视图和游戏视图中绘制可视化线条，以及在编辑器中从脚本暂停运行模式。

此页面概述了 Debug 类以及使用该类编写脚本时的常见用法。有关 Debug 类的每个成员的详尽参考，请参阅 [Debug 脚本参考](/engine/6000.0/script-reference/unity-engine/debug.md)。

## 记录错误、警告和消息##logging-errors-warnings-and-messages

Unity 本身有时会将错误、警告和消息记录到控制台窗口。Debug 类使您能够从您自己的代码中执行完全相同的操作，如下所示：

```
Debug.Log("This is a log message.");
Debug.LogWarning("This is a warning message!");
Debug.LogError("This is an error message!");
```

三种类型（错误、警告和消息）在控制台窗口中都有自己的图标类型。


**Frame:**
![](/api/media?file=/engine/6000.0/media/images/ConsoleShowingMessageWarningAndError.png)

写入控制台窗口的所有内容（由 Unity 或您自己的代码）也会写入到[日志文件](/engine/6000.0/manual/scripting/debugging-and-diagnostics/log-files.md)。

如果您在控制台中启用了 **Error Pause**，通过 Debug 类写入控制台的任何错误都将导致 Unity 的运行模式暂停。

您还可以选择为这些日志方法提供第二个参数，指示消息与特定游戏对象相关联，如下所示：

```
using UnityEngine;

public class DebugExample : MonoBehaviour
{    void Start()
    {
        Debug.LogWarning("I come in peace!", this.gameObject);
    }
}
```

这样做的好处是，当您在控制台中单击消息时，与该消息关联的游戏对象会在层级视图中突出显示，以便您识别与该消息相关的游戏对象。在下图中，您可以看到单击 "I come in peace!" 警告消息会突出显示 "Alien (8)" 游戏对象。


**Frame:**
![](/api/media?file=/engine/6000.0/media/images/ConsoleMessageWithContextGameObject.png)

Debug 类还提供了在场景视图和游戏视图中绘制线条的两种方法。它们是 [DrawLine](/engine/6000.0/script-reference/unity-engine/debug/draw-line.md) 和 [DrawRay](/engine/6000.0/script-reference/unity-engine/debug/draw-ray.md)。

在该示例中，一个脚本已添加到场景中的每个球体游戏对象，它使用 Debug.DrawLine 指示它与 Y 为零的平面之间的垂直距离。请注意，此示例中的最后一个参数是线条在编辑器中应保持可见的持续时间（以秒为单位）。

```
using UnityEngine;

public class DebugLineExample : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        float height = transform.position.y;
        Debug.DrawLine(transform.position, transform.position - Vector3.up * height, Color.magenta, 4);
    }
}
```

Scene 视图中的结果如下所示：


**Frame:**
![](/api/media?file=/engine/6000.0/media/images/DebugDrawLineExampleInScene.png)

## 其他资源##using-the-debug-class

* [控制台窗口](/engine/6000.0/manual/unity-editor/using-the-editor/console.md)
* [日志文件](/engine/6000.0/manual/scripting/debugging-and-diagnostics/log-files.md)
