Skip to content

Instantly share code, notes, and snippets.

@Menotdan
Created February 12, 2024 03:06
Show Gist options
  • Save Menotdan/da1e50e236f1c4d8d2a26b38416a02f6 to your computer and use it in GitHub Desktop.
Save Menotdan/da1e50e236f1c4d8d2a26b38416a02f6 to your computer and use it in GitHub Desktop.
Automatically logs things to the game view in Flax Engine.
using System;
using System.Collections.Generic;
using FlaxEngine;
using FlaxEngine.GUI;
namespace Game;
public class OutputLogger : GamePlugin
{
private const bool ENABLED = true;
private VerticalPanel _logs;
private class LogMessage
{
public float Time;
public Label Log;
}
private List<LogMessage> _logMessages;
public override void Initialize()
{
if (!ENABLED)
return;
base.Initialize();
_logMessages = new List<LogMessage>();
_logs = new VerticalPanel
{
Parent = RootControl.GameRoot,
AnchorPreset = AnchorPresets.TopLeft,
X = 0,
Y = 0,
Width = Screen.Size.X / 4,
Height = Screen.Size.Y / 4,
//BackgroundColor = Color.White,
};
Debug.Logger.LogHandler.SendLog += LoggerTriggered;
Scripting.Update += Update;
}
private void Trim()
{
if (_logMessages.Count > 4)
{
DeleteLog(0);
}
}
private void DeleteLog(int index)
{
_logMessages[index].Log.Parent = null;
_logMessages.RemoveAt(index);
}
private void LoggerTriggered(LogType level, string msg, FlaxEngine.Object obj, string stackTrace)
{
Label log = _logs.AddChild<Label>();
string loggingOutput = msg.Substring(0, Math.Min(25, msg.Length));
if (msg.Length > 25)
loggingOutput += "...";
log.Text = loggingOutput;
log.Font.Size = 12;
log.HorizontalAlignment = TextAlignment.Near;
log.Height = 16;
_logMessages.Add(new LogMessage
{
Log = log,
Time = 0,
});
Trim();
}
public override void Deinitialize()
{
if (!ENABLED)
return;
base.Deinitialize();
Scripting.Update -= Update;
Debug.Logger.LogHandler.SendLog -= LoggerTriggered;
_logs.Parent = null;
}
private void Update()
{
int count = 0;
foreach (LogMessage log in _logMessages)
{
log.Time += Time.DeltaTime;
if (log.Time > 10)
{
float remaining = (log.Time - 10) / 5;
remaining = 1 - remaining;
Color color = log.Log.TextColor;
color.A = remaining;
log.Log.TextColor = color;
}
if (log.Time > 15)
{
count++;
}
}
for (int i = 0; i < count; i++)
{
DeleteLog(0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment