Debug 类用于可视化编辑器中的信息,这些信息可以帮助您了解或调查项目运行时发生的情况。例如,您可以使用该类在控制台窗口中打印消息,在 Scene 视图和 Game 视图中绘制可视化线条,以及在编辑器中从脚本暂停运行模式。
此页面概述了 Debug 类及其使用该类编写脚本时的常见用法。有关 Debug 类的每个成员的详尽参考,请参阅 Debug 脚本参考。
Unity 本身有时会将错误、警告和消息记录到控制台窗口。Debug 类使您能够从您自己的代码中执行完全相同的操作,如下所示:
Debug.Log("This is a log message.");
Debug.LogWarning("This is a warning message!");
Debug.LogError("This is an error message!");
三种类型(错误、警告和消息)在控制台窗口中都有自己的图标类型。
写入控制台窗口的所有内容(由 Unity 或您自己的代码)也会写入到日志文件 。
如果您在控制台中启用了 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)” 游戏对象。
Debug 类还提供了两种在 Scene 视图和 Game 视图中绘制线条的方法。它们是:DrawLine 和 DrawRay。
在这个例子中,一个脚本被添加到场景中的每个球体游戏对象,它使用 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 视图中的结果如下所示:
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.