Unity封装定义自己喜欢的Log类型
Unity自己的Debug.Log本身的打印模式太单一,但是Unity的Log系统支持标签识别
支持的标签:(粗体斜体大小颜色项支持Debug.Log)
b 粗体 :text
i 斜体 :text
size大小 :
color颜色:
为了查看日志时便于区分,我们这里自己封装一个类,固定的颜色显示对应的日志,也可以自己定义一种日志类型对应一种颜色,这样查看日志就不会那么单一无趣了,打开VS,新建一个MyDebug类,完成后,我们把它生成dll文件,以便以后快速集成到我们的开发中去,生成导入Unity中的dll文件的目标框架是使用.Net FrameWork 3.5,如果选择的框架是framework4.0 会报错。
代码如下:
using System;
using System.Collections.Generic;
using UnityEngine;
namespace LoggerSys
{
public class MyDebug
{
public static Dictionary MyDebugs = new Dictionary();
//是否开启日志系统
public bool DebugOut = true;
private string module;
private string color;
public string Module
{
get
{
return this.module;
}
}
private MyDebug(string module, string color)
{
this.module = module;
this.color = color;
}
public static MyDebug Create(string module, string color = "black") //用于创建自己喜欢的Log
{
if (MyDebug.MyDebugs.ContainsKey(module))
{
return MyDebug.MyDebugs[module];
}
MyDebug myDebug = new MyDebug(module, color);
MyDebug.MyDebugs.Add(module, myDebug);
return myDebug;
}
public void Log(string message)
{
if (this.DebugOut)
{
string text = string.Format("{0} |{1}| {3}| {4} ",
new object[]{
DateTime.Now.ToShortTimeString(),
"INFO",
this.color,
this.module,
message
});
Debug.Log(text); //Unity引擎使用
}
}
public void LogError(object message)
{
if (this.DebugOut)
{
string text = string.Format("{0} |{1}|{2}| {3} ",
new object[]{
DateTime.Now.ToShortTimeString(),
"ERROR",
this.module,
message
});
Debug.LogError(text); //Unity引擎使用
}
}
public void LogException(Exception exception)
{
if (this.DebugOut)
{
Debug.LogException(exception);
}
}
public void LogWarning(object message)
{
if (this.DebugOut)
{
string text = string.Format("{0} |{1}|{2}| {3} ", new object[]
{
DateTime.Now.ToShortTimeString(),
"WARNING",
this.module,
message
});
Debug.LogWarning(text);
}
}
public void LogFormat(string format, params object[] args)
{
if (this.DebugOut)
{
string text = string.Format("{0} |{1}{2}| {3} ", new object[]
{
DateTime.Now.ToShortTimeString(),
"INFO",
this.module,
format
});
Debug.LogFormat(text, args);
}
}
public void LogErrorFormat(string format, params object[] args)
{
if (this.DebugOut)
{
string text = string.Format("{0} |{1}|{2}| {3} ", new object[]
{
DateTime.Now.ToShortTimeString(),
"ERROR",
this.module,
format
});
Debug.LogErrorFormat(text, args);
}
}
public void LogWarningFormat(string format, params object[] args)
{
if (this.DebugOut)
{
string text = string.Format("{0} |{1}|{2}| {3} ", new object[]
{
DateTime.Now.ToShortTimeString(),
"WARNING",
this.module,
format
});
Debug.LogErrorFormat(text, args);
}
}
public static MyDebug Sys = MyDebug.Create("SYS", "#000000ff");
public static MyDebug Res = MyDebug.Create("RES", "#008000ff");
public static MyDebug Net = MyDebug.Create("NET", "#add8e6ff");
public static MyDebug UI = MyDebug.Create("UI", "#008080ff");
}
}
效果图如下: