unity 打包完成之后 (黑色控制台提示)

来源:互联网 发布:网络电视直播软件apk 编辑:程序博客网 时间:2024/04/30 05:39

unity 打包完成之后 (黑色控制台提示)

习惯了原来C/S结构的开发,需要在unity里调用控制台来打印游戏日志,而不影响游戏的画面,我们需要调用windows API来处理一些事情。废话不多说了,直接上干货,调用windows API来显示控制台。代码如下:

using UnityEngine;
using System.Runtime.InteropServices;
using System;
using System.IO;
using Microsoft.Win32.SafeHandles;
public static class Common
{
[DllImport(“kernel32.dll”, SetLastError = true)]
static extern bool AllocConsole();

private const int STD_OUTPUT_HANDLE = -11;[DllImport("kernel32.dll", SetLastError = true)]static extern bool FreeConsole();[DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] static extern IntPtr GetStdHandle(int nStdHandle);static TextWriter oldOutput;internal static  void  StartWriteline(){    AllocConsole();    oldOutput = Console.Out;    try    {        IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);        SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);        FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);        System.Text.Encoding encoding = System.Text.Encoding.ASCII;        StreamWriter standardOutput = new StreamWriter(fileStream, encoding);        standardOutput.AutoFlush = true;        Console.SetOut(standardOutput);    }    catch (System.Exception ex)    {        Debug.Log("Couldn't redirect output: " + ex.Message);    }}internal static void CLoseWriteline(){    Console.SetOut(oldOutput);    FreeConsole();}

}
有需要的人直接把代码拷贝下来就可以用了,这种控制台不建议在编辑器模式下使用,在编辑器模式下会带来不必要的麻烦。

0 0
原创粉丝点击