A Colorful Logging Component for Unity

A Colorful Logging Component for Unity

Problem:

I want to add logging to a GameObject that can be called via code or wired up via the inspector. I also want to specify the color of the logs in the inspector so that I can easily distinguish the messages in the debug console.

Solution:

Use the code below to create a new component that you can add to GameObjects. You can then access the logging methods via GetComponent<LoggingBehavior>() or wire up logging calls in the inspector.

using UnityEngine;

public class LoggingBehavior : MonoBehaviour
{
    private const string FORMAT = "<color=#{0}><b>{1}</b>: {2}</color>";

    [Header("Settings")]
    [Space(10)]

    [Tooltip("Set the color for log messages")]
    [SerializeField] private Color logColor = Color.white;

    // Private State
    private string _htmlColor;

    // Unity Lifecycle

    private void Awake()
    {
        _htmlColor = ColorUtility.ToHtmlStringRGB(logColor);
    }

    // Public API

    public void LogInfo(string message)
    {
        Debug.LogFormat(gameObject, FORMAT, _htmlColor, gameObject.name, message);
    }

    public void LogWarning(string message)
    {
        Debug.LogWarningFormat(gameObject, FORMAT, _htmlColor, gameObject.name, message);
    }

    public void LogError(string message)
    {
        Debug.LogErrorFormat(gameObject, FORMAT, _htmlColor, gameObject.name, message);
    }

}

The results, in this example a timer component that invokes UnityEvents is connected to the LoggingBehavior component.

image.png