本文章由cartzhang编写,转载请注明出处。 所有权利保留。

文章链接:http://blog.csdn.net/cartzhang/article/details/49884507

作者:cartzhang

第一部分博客链接: http://blog.csdn.net/cartzhang/article/details/49818953

第一部分博客链接

Github 地址:https://github.com/cartzhang/TestConsoleWindow  github console window

一、你还是想要一个控制台来显示信息?

为什么呢?这样就不会占用Unity本身的GUI的显示,不去调用Unity的渲染,转而该为Windows的渲染了。

是不是很惬意,花费少了,还更灵活了。

好极了。

二、你都需要些什么?

当然是一个控制台窗口和写到控制台的输入了。

代码是歪果仁写的,但是很好用。

首先,输入的代码:
名字为ConsoleInput.cs
using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO; namespace ConsoleTestWindows
{
public class ConsoleInput
{
//public delegate void InputText( string strInput );
public event System.Action<string> OnInputText;
public string inputString; public void ClearLine()
{
//System.Text.Encoding test = Console.InputEncoding;
Console.CursorLeft = 0;
Console.Write( new String( ' ', Console.BufferWidth ) );
Console.CursorTop--;
Console.CursorLeft = 0;
} public void RedrawInputLine()
{
if ( inputString.Length == 0 ) return; if ( Console.CursorLeft > 0 )
ClearLine(); System.Console.ForegroundColor = ConsoleColor.Green;
System.Console.Write( inputString );
} internal void OnBackspace()
{
if ( inputString.Length < 1 ) return; inputString = inputString.Substring( 0, inputString.Length - 1 );
RedrawInputLine();
} internal void OnEscape()
{
ClearLine();
inputString = "";
} internal void OnEnter()
{
ClearLine();
System.Console.ForegroundColor = ConsoleColor.Green;
System.Console.WriteLine( "> " + inputString ); var strtext = inputString;
inputString = ""; if ( OnInputText != null )
{
OnInputText( strtext );
}
} public void Update()
{
if ( !Console.KeyAvailable ) return;
var key = Console.ReadKey(); if ( key.Key == ConsoleKey.Enter )
{
OnEnter();
return;
} if ( key.Key == ConsoleKey.Backspace )
{
OnBackspace();
return;
} if ( key.Key == ConsoleKey.Escape )
{
OnEscape();
return;
} if ( key.KeyChar != '\u0000' )
{
inputString += key.KeyChar;
RedrawInputLine();
return;
}
}
}
}

然后,你还需要一个控制台窗口


如下:
using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO; namespace ConsoleTestWindows
{
/// <summary>
/// Creates a console window that actually works in Unity
/// You should add a script that redirects output using Console.Write to write to it.
/// </summary>
public class ConsoleWindow
{
TextWriter oldOutput; public void Initialize()
{
//
// Attach to any existing consoles we have
// failing that, create a new one.
//
if ( !AttachConsole( 0x0ffffffff ) )
{
AllocConsole();
} oldOutput = Console.Out; try
{
IntPtr stdHandle = GetStdHandle( STD_OUTPUT_HANDLE );
Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.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 e )
{
Debug.Log( "Couldn't redirect output: " + e.Message );
}
} public void Shutdown()
{
Console.SetOut( oldOutput );
FreeConsole();
} public void SetTitle( string strName )
{
SetConsoleTitle( strName );
} private const int STD_OUTPUT_HANDLE = -11; [DllImport( "kernel32.dll", SetLastError = true )]
static extern bool AttachConsole( uint dwProcessId ); [DllImport( "kernel32.dll", SetLastError = true )]
static extern bool AllocConsole(); [DllImport( "kernel32.dll", SetLastError = true )]
static extern bool FreeConsole(); [DllImport( "kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall )]
private static extern IntPtr GetStdHandle( int nStdHandle ); [DllImport( "kernel32.dll" )]
static extern bool SetConsoleTitle( string lpConsoleTitle );
}
}

三、输入和窗口准备齐全了,问题来了。


当你试图编译代码时候,你会发现居然编译报错,各种找不到。
Console.CursorLeft等大量的方法和变量都找不到。

这是因为Untiy5 默认的目标框架Unity3.5 .net sbu base class Libraries.。在Player Setting中,可设置为.Net 2.0。


这就可以改变了VS下的编译环境了。
但是要是你想要修改编译环境为你想要的其他呢?

四、那么问题来了?怎么修改编译环境的目标框架呢?



你肯定不会是想出这个问题的第一人?所以那就有人来解决问题;
动态的修改你的FrameWork,就可以解答这个问题。

代码:UpgradeVSProject.cs

//#define USE_UPGRADEVS
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Text.RegularExpressions; class UpgradeVSProject : AssetPostprocessor
{
#if USE_UPGRADEVS
private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
string currentDir = Directory.GetCurrentDirectory();
string[] slnFile = Directory.GetFiles(currentDir, "*.sln");
string[] csprojFile = Directory.GetFiles(currentDir, "*.csproj"); bool hasChanged = false;
if (slnFile != null)
{
for (int i = 0; i < slnFile.Length; i++)
{
if (ReplaceInFile(slnFile[i], "Format Version 10.00", "Format Version 11.00"))
hasChanged = true;
}
} if (csprojFile != null)
{
for (int i = 0; i < csprojFile.Length; i++)
{
if (ReplaceInFile(csprojFile[i], "ToolsVersion=\"3.5\"", "ToolsVersion=\"4.0\""))
hasChanged = true; if (ReplaceInFile(csprojFile[i], "<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>", "<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>"))
hasChanged = true;
}
} if (hasChanged)
{
Debug.LogWarning("Project is now upgraded to Visual Studio 2010 Solution!");
}
else
{
Debug.Log("Project-version has not changed...");
}
} static private bool ReplaceInFile(string filePath, string searchText, string replaceText)
{
StreamReader reader = new StreamReader(filePath);
string content = reader.ReadToEnd();
reader.Close(); if (content.IndexOf(searchText) != -1)
{
content = Regex.Replace(content, searchText, replaceText);
StreamWriter writer = new StreamWriter(filePath);
writer.Write(content);
writer.Close(); return true;
} return false;
}
#endif
}

同样,我写了代码屏蔽的宏定义。使用的时候启用就可以了。

就可以自动升高版本到4.0上,当然你也可以修改代码来升高到其他版本的。

注意:这个代码很明显,需要放置在Editor文件夹下。

五、测试结果

我写了个几行的测试代码:
using UnityEngine;
using System.Collections; public class Tes : MonoBehaviour { // Use this for initialization
void Start () { } // Update is called once per frame
void Update ()
{
if (Input.GetKey(KeyCode.A))
{
Debug.Log("this is debug log");
System.Console.WriteLine("this is system console write line");
} }
}

结果就出来了:



别告诉我,这不是你想要的控制台窗口。
你看看,在写Log时,会不会造成你的游戏卡顿了呢??


---------THE END------------------------

若有问题,请随时联系!
非常感谢!!




Unity 实现Log实时输出到屏幕或控制台上<二>的更多相关文章

  1. Unity 实现Log实时输出到屏幕或控制台上<一>

    本文章由cartzhang编写,转载请注明出处. 所有权利保留. 文章链接:http://blog.csdn.net/cartzhang/article/details/49818953 作者:car ...

  2. unity收集log工具

    参考 yusong:http://www.xuanyusong.com/archives/2477 凉鞋     :https://www.cnblogs.com/liangxiegame/p/Uni ...

  3. [Linux]屏幕输出控制

    专门的术语叫做ANSI Escape sequences(ANSI Escape codes),题目并不恰当,与其说是屏幕输出控制,不如说是通过bash在兼容VT100的终端上进行输出. 主要有以下类 ...

  4. .NET Core下的日志(3):如何将日志消息输出到控制台上

    当我们利用LoggerFactory创建一个Logger对象并利用它来实现日志记录,这个过程会产生一个日志消息,日志消息的流向取决于注册到LoggerFactory之上的LoggerProvider. ...

  5. java 在控制台上输入密码时,密码不显示在控制台上

    用下面的方法可以实现在控制台上输入密码时,密码不显示在控制台上:Console cons=System.console(); System.out.print(" 密码:"); c ...

  6. 大数据调错系列之hadoop在开发工具控制台上打印不出日志的解决方法

    (1)在windows环境上配置HADOOP_HOME环境变量 (2)在eclipse上运行程序 (3)注意:如果eclipse打印不出日志,在控制台上只显示 1.log4j:WARN No appe ...

  7. eclipse:eclipse for java EE环境下如何配置tomcat服务器,并让tomcat服务器显示在控制台上,将Web应用部署到tomcat中

    eclipse环境下如何配置tomcat 打开Eclipse,单击"Window"菜单,选择下方的"Preferences".  单击"Server& ...

  8. Ubuntu上运行Blender,在控制台上查看运行结果

    1.首先在控制台打开Blender. 具体操作:找到Blender的安装路径,我的是:/home/lcx/下载/blender-2.78c-linux-glibc219-x86_64 $cd /hom ...

  9. Java:IO流的综合用法(从键盘录入数据并打印在控制台上)

    import java.io.*; public class IOTestDouble { public static void main(String[] args)throws Exception ...

随机推荐

  1. APP信息获取接口

    https://itunes.apple.com/lookup?id=APPID&callback=2 http://myapp.com/cgi-bin/mapp/mapp_info?type ...

  2. 51nod 1562 玻璃切割 (STL map+一点点的思考)

    1562 玻璃切割 题目来源: CodeForces 基准时间限制:1.5 秒 空间限制:131072 KB 分值: 20 难度:3级算法题 现在有一块玻璃,是长方形的(w 毫米× h 毫米),现在要 ...

  3. Django------->>>modle

    import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "modletest.settings") ...

  4. 如何使用外部插件picker

    近日有需求做一个职业选择弹框,在网上搜了半天也没合适的: 暴躁大佬协助我DIY一个插件,直接使用,顺滑流畅,随心所欲!特别鸣谢@一样菜 不多BB了,直接撸代码: 引用写在上面: /* 更改职业 */ ...

  5. HDU Integer's Power(容斥原理)

    题意 求[l,r]的最大指数和(1<=l,r<=10^18) 最大指数和(如64=8^2=4^3=2^6,所以64的最大指数和是6) 题解 很明显我们可以先求出[1,n]的最大指数和,然后 ...

  6. AES对称加密util

    package cn.com.qmhd.oto.common; import java.security.Key; import java.security.NoSuchAlgorithmExcept ...

  7. 题解 UVA12206 【Stammering Aliens】

    终于A了这道题啊(坑啊) 教练说:这道题不能用map吧,复杂度不一个O(nlogn)吗 于是我就一直想不出来,然后看题解代码,一看就是map... 所以我就在想,那复杂度是不是也不是O(nlogn)呢 ...

  8. G4Studio+extjs+highcharts 下在ext4j的panel中放入hightCharts图表

    在G4Studio+extjs下.创建一个panel,然后将highCharts图表放入panel中.实现方法例如以下: 首先简单给出的部分代码: Ext.onReady(function() { v ...

  9. [Mobx] Using mobx to isolate a React component state

    React is great for diffing between Virtual-DOM and rendering it to the dom. It also offers a naïve s ...

  10. Dubbo分布式服务框架入门(附project)

    要想了解Dubbo是什么,我们不防先了解它有什么用. 使用场景:比方我想开发一个网上商城项目.这个网上商城呢,比較复杂.分为pc端web管理后台.微信端销售公众号,那么我们分成四个项目,pc端站点,微 ...