noobtuts

Detect Headless Mode in Unity

Unity can build Linux executables in what's called Headless Mode which is useful if we want to run game servers without any graphics. The Headless mode runs low on memory and with maximum performance to make servers as fast as possible.

The UNET NetworkManager HUD offers buttons to start a client, host and server. But if we run the server in headless mode, then we can't actually press any buttons because we don't see them. In those cases it would be incredibly useful to detect the Headless Mode and then automatically start a dedicated server like this:

void Awake() {
    if (IsHeadless()) {
        print("headless mode detected");
        StartServer();
    }
}

Unity doesn't have any kind of IsHeadless flag yet, but luckily we found a way to detect it anyways:

using UnityEngine.Rendering;

// detect headless mode (which has graphicsDeviceType Null)
bool IsHeadless() {
    return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null;
}

This function works because Unity simulates a graphics card in Headless Mode, and that graphics card has the device type Null.

And that's all there is too it!