关于怎么在手机上查看游戏log的方法。
代码如下:
using System.Collections.Generic;
using UnityEngine;
class TestConsole : MonoBehaviour
{
struct Log
{
public string message;
public string stackTrace;
public LogType type;
}
//是否限制Log的最大长度
public bool restrictLogCount = true;
private int maxLogs = 1000;
readonly List<Log> logs = new List<Log>();
Vector2 scrollPosition;
bool visible;//显示Log面板
bool collapse;//合并相同内容
static readonly Dictionary<LogType, Color> logTypeColors = new Dictionary<LogType, Color>
{
{ LogType.Assert, Color.white },
{ LogType.Error, Color.red },
{ LogType.Exception, Color.red },
{ LogType.Log, Color.white },
{ LogType.Warning, Color.yellow },
};
const string windowTitle = "Console";
const int margin = 20;
static readonly GUIContent clearLabel = new GUIContent("Clear", "Clear the contents of the console.");
static readonly GUIContent collapseLabel = new GUIContent("Collapse", "Hide repeated messages.");
readonly Rect titleBarRect = new Rect(0, 0, 600, 20);
Rect windowRect = new Rect(margin, margin, Screen.width - (margin * 2), Screen.height - (margin * 2));
void OnEnable()
{
#if UNITY_5
Application.logMessageReceived += HandleLog;
#else
Application.RegisterLogCallback(HandleLog);
#endif
}
void OnDisable()
{
#if UNITY_5
Application.logMessageReceived -= HandleLog;
#else
Application.RegisterLogCallback(null);
#endif
}
void OnGUI()
{
if(GUI.Button(new Rect(0,0,100,30), "ConsoleLog"))
{
visible = !visible;
}
if (!visible)
{
return;
}
windowRect = GUILayout.Window(123456, windowRect, DrawConsoleWindow, windowTitle, GUILayout.Width(600), GUILayout.Height(300));
}
void DrawConsoleWindow(int windowID)
{
DrawLogsList();
DrawToolbar();
GUI.DragWindow(titleBarRect);
}
void DrawLogsList()
{
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
for (var i = 0; i < logs.Count; i++)
{
var log = logs[i];
if (collapse && i > 0)
{
var previousMessage = logs[i - 1].message;
if (log.message == previousMessage)
{
continue;
}
}
GUIStyle bb = new GUIStyle();
bb.wordWrap = true;
bb.normal.textColor = logTypeColors[log.type];
GUILayout.Label(log.message, bb, GUILayout.Width(600));
}
GUILayout.EndScrollView();
GUI.contentColor = Color.white;
}
void DrawToolbar()
{
GUILayout.BeginHorizontal();
if (GUILayout.Button(clearLabel, GUILayout.Width(500), GUILayout.Height(20)))
{
logs.Clear();
}
collapse = GUILayout.Toggle(collapse, collapseLabel, GUILayout.ExpandWidth(false), GUILayout.Width(90), GUILayout.Height(20));
GUILayout.EndHorizontal();
}
void HandleLog(string message, string stackTrace, LogType type)
{
logs.Add(new Log{
message = message,
stackTrace = stackTrace,
type = type,
});
TrimExcessLogs();
}
void TrimExcessLogs()
{
if (!restrictLogCount)
{
return;
}
var amountToRemove = Mathf.Max(logs.Count - maxLogs, 0);
if (amountToRemove == 0)
{
return;
}
logs.RemoveRange(0, amountToRemove);
}
}
效果如图: