How to get Javascript's console.log in Unity/C#


How many times have I done this?

Debug.Log(thing, otherThing);

Only for Unity slap me upside the head with a mutter of disapproval. I sigh and make two Debug statements or add a + " " + in between. Or use the fancy $"{thing} {otherThing}" string interpolation majigger. But I want my console.log(thing, otherThing, otherOtherThing) and I want it to work as I expect, damn it all! So let's do that.

// Console.cs
using System;
using UnityEngine;
public static class Console {
    public static void Log(params object[] objects) {
        LogMessage(Debug.Log, objects);
    }
    public static void Warn(params object[] objects) {
        LogMessage(Debug.LogWarning, objects);
    }
    public static void Error(params object[] objects) {
        LogMessage(Debug.LogError, objects);
    }
    static void LogMessage(Action<object> logger, params object[] objects) {
        string output = "";
        foreach (object obj in objects) {
            output += $"{obj} ";
        }
        logger(output.Trim());
    }
}

And we're done. Let's give 'er a spin:

// Your code
Console.Log("Oh?", "What's this?", "This is what I wanted?!", new Vector3(1, 2, 3));
// Output:
[23:49:59] Oh? What's this? This is what I wanted?! (1.0, 2.0, 3.0)

Sometimes we expect too much from tools handed to us. Sometimes we need to make our own tools. I'm resisting the urge to post Thanos right now. You know the one.

On a related note, itch.io's CMS editor removes all the new lines from my code examples. So it's harder to read without the proper whitespace. Just know I'm not doing it on purpose.

Get Against the Tide

Download NowName your own price

Leave a comment

Log in with itch.io to leave a comment.