Unity BatchMode Console

Wednesday, April 23, 2014

If you've made a game that has a dedicated server in Unity using -batchmode you probably noticed that when you use Console.Print it doesn't print to the console. And it's pretty hard to make it happen.

So here's a couple of classes that we use in Rust's dedicated server. This is Windows Only. Download them here.

2014-04-23_15-48-13 Here's how we use it in Rust:
public class ServerConsole : MonoBehaviour
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
 
	Windows.ConsoleWindow console = new Windows.ConsoleWindow();
	Windows.ConsoleInput input = new Windows.ConsoleInput();
 
	string strInput;
	
	//
	// Create console window, register callbacks
	//
	void Awake() 
	{
		DontDestroyOnLoadgameObject );
 
		console.Initialize();
		console.SetTitle"Rust Server" );
 
		input.OnInputText += OnInputText;
 
		Application.RegisterLogCallbackHandleLog );
 
		Debug.Log"Console Started" );
	}
 
	//
	// Text has been entered into the console
	// Run it as a console command
	//
	void OnInputTextstring obj )
	{
		ConsoleSystem.Runobjtrue );
	}
 
	//
	// Debug.Log* callback
	//
	void HandleLogstring messagestring stackTraceLogType type )
	{
		if ( type == LogType.Warning )		
			System.Console.ForegroundColor = ConsoleColor.Yellow;
		else if ( type == LogType.Error )	
			System.Console.ForegroundColor = ConsoleColor.Red;
		else								
			System.Console.ForegroundColor = ConsoleColor.White;
 
		// We're half way through typing something, so clear this line ..
		if ( Console.CursorLeft != 0 )
			input.ClearLine();
 
		System.Console.WriteLinemessage );
 
		// If we were typing something re-add it.
		input.RedrawInputLine();
	}
 
	//
	// Update the input every frame
	// This gets new key input and calls the OnInputText callback
	//
	void Update()
	{
		input.Update();
	}
 
	//
	// It's important to call console.ShutDown in OnDestroy
	// because compiling will error out in the editor if you don't
	// because we redirected output. This sets it back to normal.
	//
	void OnDestroy()
	{
		console.Shutdown();
	}
 
#endif
}
Turn your phone to view blog list