My goal: to make a Unity based dedicated multiplayer server, with minimum bloat, such as turning off the renderer, and spawning a console window for text output.
My progress thus far: Running a unity application with the command line arguments “-batchmode -nographics” will effectively prevent Unity from opening a window (this works both with the editor, and a compiled Unity application). To spawn a console window, I am using unmanaged code on a “manager” GameObject as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using UnityEngine;
public class GameManager : MonoBehaviour {
[DllImport("kernel32.dll")]
private static extern bool AllocConsole();
private static extern IntPtr GetStdHandle(UInt32 nStdHandle);
private static extern void SetStdHandle(UInt32 nStdHandle, IntPtr handle);
private const UInt32 StdOutputHandle = 0xFFFFFFF5;
private TextWriter writer;
// Use this for initialization
void Start () {
DontDestroyOnLoad(this);
StartConsole();
WriteLine("Console Ready");
}
// Update is called once per frame
void Update () {
}
void StartConsole() {
AllocConsole();
// stdout's handle seems to always be equal to 7
IntPtr defaultStdout = new IntPtr(7);
IntPtr currentStdout = GetStdHandle(StdOutputHandle);
if (currentStdout != defaultStdout)
// reset stdout
SetStdHandle(StdOutputHandle, defaultStdout);
// reopen stdout
writer = new StreamWriter(Console.OpenStandardOutput())
{ AutoFlush = true };
Console.SetOut(writer);
}
void WriteLine(string line) {
writer.WriteLine(line);
}
}
When I run this scene in the editor, a console window is created, but then Unity crashes. Same with a standalone compiled application. It crashes before displaying the text “Console Ready”.
-
Does anyone have any ideas or tips on what I may be doing wrong with this?
-
Is there perhaps a different (possibly better) approach? Aside from networking, I still need some form of scene management and physics for the server to properly do game logic. It would be great if I could use just the parts of Unity that are essential to running a server, for maximum efficiency.