接上一个汽车控制,现在我需要实现的是在汽车跑的时候实时打印它的速度在屏幕上,我们都知道如果直接Debug.Log()的话,它打印在控制台上,我们只需要制作一个GUI窗口,打印log就可以了,这个功能是一个外国蜀黍的,我拿来改了一下,灰常对不起,我找了半天找不到原博地址了,我说一下修改的内容吧,由于原程序虽然可以打印log,但是不能和控制台一样往下实时刷新,它的滚动条不能自己往下刷新,你要看还要用鼠标往下拉,这样很不方便。
我怎么做的呢,其实很简单,加一个协程(start和clearlog函数)就好了,我定了每0.1s定时清空一次log,看上去和实时刷新差不多,效果图,为什么不能每帧刷新呢?因为FixedUpdate的每一帧和Update的帧的长度不一样,神奇~
我这个人美感不行,你可以自己调调位置界面颜色之类的。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Consolation
{
/// <summary>
/// A console to display Unity's debug logs in-game.
/// </summary>
class TestConsole : MonoBehaviour
{
//#if USE_TESTCONSOLE
struct Log
{
public string message;
public string stackTrace;
public LogType type;
}
#region Inspector Settings
/// <summary>
/// The hotkey to show and hide the console window.
/// </summary>
public KeyCode toggleKey = KeyCode.BackQuote;
/// <summary>
/// Whether to open the window by shaking the device (mobile-only).
/// </summary>
public bool shakeToOpen = true;
/// <summary>
/// The (squared) acceleration above which the window should open.
/// </summary>
public float shakeAcceleration = 3f;
/// <summary>
/// Whether to only keep a certain number of logs.
///
/// Setting this can be helpful if memory usage is a concern.
/// </summary>
public bool restrictLogCount = false;
/// <summary>
/// Number of logs to keep before removing old ones.
/// </summary>
public int maxLogs = 1000;
#endregion
readonly List<Log> logs = new List<Log>();
Vector2 scrollPosition;
bool visible;
bool collapse;
// Visual elements:
private void Start()
{
StartCoroutine(ClearLog());
}
IEnumerator ClearLog()
{
yield return new WaitForSeconds(0.1f);
logs.Clear();
yield return StartCoroutine(ClearLog());
}
static readonly Dictionary<LogType, Color> logTypeColors = new Dictionary<LogType, Color>
{
//Log类型
{ LogType.Assert, Color.white },
{ LogType.Error, Color.red },
{ LogType.Exception, Color.red },
{ LogType.Log, Color.white },
{ LogType.Warning, Color.yellow },
};
//窗口设置
const string windowTitle = "Speed";
const int margin = 100;
// 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, 1000, 20);
Rect windowRect = new Rect(500, 0, Screen.width - (margin * 5), Screen.height - (margin * 6));
void OnEnable()
{
//#if UNITY_5
Application.logMessageReceived += HandleLog;
//#else
// Application.logMessageReceived(HandleLog);
// Application.RegisterLogCallback(HandleLog);
//#endif
}
void OnDisable()
{
//#if UNITY_5
Application.logMessageReceived -= HandleLog;
//#else
// Application.RegisterLogCallback(null);
//#endif
}
void Update()
{
if (Input.GetKeyDown(toggleKey))
{
visible = !visible;
}
if (shakeToOpen && Input.acceleration.sqrMagnitude > shakeAcceleration)
{
visible = true;
}
}
void OnGUI()
{
if (!visible)
{
return;
}
//
windowRect = GUILayout.Window(123456, windowRect, DrawConsoleWindow, windowTitle);
}
/// <summary>
/// Displays a window that lists the recorded logs.
/// </summary>
/// <param name="windowID">Window ID.</param>
void DrawConsoleWindow(int windowID)
{
DrawLogsList();
DrawToolbar();
// Allow the window to be dragged by its title bar.
GUI.DragWindow(titleBarRect);
}
/// <summary>
/// Displays a scrollable list of logs.
/// </summary>
void DrawLogsList()
{
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
// Iterate through the recorded logs.
for (var i = 0; i < logs.Count; i++)
{
var log = logs[i];
// Destroy(logs[i - 1]);
// Combine identical messages if collapse option is chosen.
if (collapse && i > 0)
{
var previousMessage = logs[i - 1].message;
if (log.message == previousMessage)
{
continue;
}
}
GUI.contentColor = logTypeColors[log.type];
GUILayout.Label(log.message);
}
GUILayout.EndScrollView();
// Ensure GUI colour is reset before drawing other components.
GUI.contentColor = Color.white;
}
/// <summary>
/// Displays options for filtering and changing the logs list.
/// </summary>
void DrawToolbar()
{
GUILayout.BeginHorizontal();
//if (GUILayout.Button(clearLabel))
//{
// logs.Clear();
//}
// collapse = GUILayout.Toggle(collapse, collapseLabel, GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal();
}
/// <summary>
/// Records a log from the log callback.
/// </summary>
/// <param name="message">Message.</param>
/// <param name="stackTrace">Trace of where the message came from.</param>
/// <param name="type">Type of message (error, exception, warning, assert).</param>
void HandleLog(string message, string stackTrace, LogType type)
{
logs.Add(new Log
{
message = message,
stackTrace = stackTrace,
type = type,
});
TrimExcessLogs();
}
/// <summary>
/// Removes old logs that exceed the maximum number allowed.
/// </summary>
void TrimExcessLogs()
{
if (!restrictLogCount)
{
return;
}
var amountToRemove = Mathf.Max(logs.Count - maxLogs, 0);
if (amountToRemove == 0)
{
return;
}
logs.RemoveRange(0, amountToRemove);
}
//#endif
}
}
不得不说,协程真的太好用了啊,按~这个键可以调出这个GUI,再次抱歉。
后续:
在这里打印出debug信息,这种做法是可以的,但是显示速度变量之类的最好的方法是在OnGUI函数里调用,由于这个是每帧都会执行一次,所以看上去是实时刷新。上面的做法可以但不够简洁。
例如
void OnGUI()
{
if (!visible)
{
GUI.backgroundColor = Color.black;
float guiWidth = Screen.width / 2 - 200;
GUI.backgroundColor = Color.blue;
GUI.Button(new Rect(Screen.width - 30 - guiWidth, 165, 10, Mathf.Clamp(((-motorInput) * 100), -100, 0)), "");
GUI.backgroundColor = Color.red;
GUI.Button(new Rect(Screen.width - 45 - guiWidth, 165, 10, Mathf.Clamp((-brakeInput * 100), -100, 0)), "");
}
}