Monday, July 21, 2014

A workaround for allowing multiple callbacks to Application.RegisterLogCallback

Unity only supports a single delegate to be registered with Application.RegisterLogCallback, which is unfortunate because it means that two independent plugins can't make separate use of it.

A bug was filed for this issue last year: http://feedback.unity3d.com/suggestions/change-application-dot-registerlogcallback-to-allow-multiple-callbacks

To get around this, I wrote a class to allow for multiple callbacks to be registered. Make sure let only this class make the call to Application.RegisterLogCallback.
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Unity only handles a single delegate registered with Application.RegisterLogCallback
/// http://feedback.unity3d.com/suggestions/change-application-dot-registerlogcallback-to-allow-multiple-callbacks
/// 
/// This class is used to work around that by allowing multiple delegates to hook to the log callback.
/// </summary>
public static class LogCallbackHandler
{
    private static readonly List<Application.LogCallback> callbacks;

    static LogCallbackHandler()
    {
        callbacks = new List<Application.LogCallback>();

        Application.RegisterLogCallback(HandleLog);
    }

    /// <summary>
    /// Register a delegate to be called on log messages.
    /// </summary>
    /// <param name="logCallback"></param>
    public static void RegisterLogCallback(Application.LogCallback logCallback)
    {
        callbacks.Add(logCallback);
    }

    private static void HandleLog(string condition, string stackTrace, LogType type)
    {
        for (var i = 0; i < callbacks.Count; i++)
        {
            callbacks[i](condition, stackTrace, type);
        }
    }
}