Unity log 自定义输出

//#define USE_TESTCONSOLE
using System.Collections.Generic;
using UnityEngine;


namespace Consolation
{
    /// <summary>
    /// A console to display Unity's debug logs in-game.
    /// </summary>
    class TestConsole : MonoBehaviour
    {
#if USE_TESTCONSOLE
        struct Log
        {
            public string message;
            public string stackTrace;
            public LogType type;
        }


        #region Inspector Settings


        /// <summary>
        /// The hotkey to show and hide the console window.
        /// </summary>
        public KeyCode toggleKey = KeyCode.BackQuote;


        /// <summary>
        /// Whether to open the window by shaking the device (mobile-only).
        /// </summary>
        public bool shakeToOpen = true;


        /// <summary>
        /// The (squared) acceleration above which the window should open.
        /// </summary>
        public float shakeAcceleration = 3f;


        /// <summary>
        /// Whether to only keep a certain number of logs.
        ///
        /// Setting this can be helpful if memory usage is a concern.
        /// </summary>
        public bool restrictLogCount = false;


        /// <summary>
        /// Number of logs to keep before removing old ones.
        /// </summary>
        public int maxLogs = 1000;


        #endregion


        readonly List<Log> logs = new List<Log>();
        Vector2 scrollPosition;
        bool visible;
        bool collapse;


        // Visual elements:


        static readonly Dictionary<LogType, Color> logTypeColors = new Dictionary<LogType, Color>
{
{ LogType.Assert, Color.white },
{ LogType.Error, Color.red },
{ LogType.Exception, Color.red },
{ LogType.Log, Color.white },
{ LogType.Warning, Color.yellow },
};


        const string windowTitle = "Console";
        const int margin = 20;
        static readonly GUIContent clearLabel = new GUIContent("Clear", "Clear the contents of the console.");
        static readonly GUIContent collapseLabel = new GUIContent("Collapse", "Hide repeated messages.");


        readonly Rect titleBarRect = new Rect(0, 0, 10000, 20);
        Rect windowRect = new Rect(margin, margin, Screen.width - (margin * 2), Screen.height - (margin * 2));


        void OnEnable()
        {
#if UNITY_5
Application.logMessageReceived += HandleLog;
#else
            Application.RegisterLogCallback(HandleLog);
#endif
        }


        void OnDisable()
        {
#if UNITY_5
Application.logMessageReceived -= HandleLog;
#else
            Application.RegisterLogCallback(null);
#endif
        }


        void Update()
        {
            if (Input.GetKeyDown(toggleKey))
            {
                visible = !visible;
            }


            if (shakeToOpen && Input.acceleration.sqrMagnitude > shakeAcceleration)
            {
                visible = true;
            }
        }


        void OnGUI()
        {
            if (!visible)
            {
                return;
            }


            windowRect = GUILayout.Window(123456, windowRect, DrawConsoleWindow, windowTitle);
        }


        /// <summary>
        /// Displays a window that lists the recorded logs.
        /// </summary>
        /// <param name="windowID">Window ID.</param>
        void DrawConsoleWindow(int windowID)
        {
            DrawLogsList();
            DrawToolbar();


            // Allow the window to be dragged by its title bar.
            GUI.DragWindow(titleBarRect);
        }


        /// <summary>
        /// Displays a scrollable list of logs.
        /// </summary>
        void DrawLogsList()
        {
            scrollPosition = GUILayout.BeginScrollView(scrollPosition);


            // Iterate through the recorded logs.
            for (var i = 0; i < logs.Count; i++)
            {
                var log = logs[i];


                // Combine identical messages if collapse option is chosen.
                if (collapse && i > 0)
                {
                    var previousMessage = logs[i - 1].message;


                    if (log.message == previousMessage)
                    {
                        continue;
                    }
                }


                GUI.contentColor = logTypeColors[log.type];
                GUILayout.Label(log.message);
            }


            GUILayout.EndScrollView();


            // Ensure GUI colour is reset before drawing other components.
            GUI.contentColor = Color.white;
        }


        /// <summary>
        /// Displays options for filtering and changing the logs list.
        /// </summary>
        void DrawToolbar()
        {
            GUILayout.BeginHorizontal();


            if (GUILayout.Button(clearLabel))
            {
                logs.Clear();
            }


            collapse = GUILayout.Toggle(collapse, collapseLabel, GUILayout.ExpandWidth(false));


            GUILayout.EndHorizontal();
        }


        /// <summary>
        /// Records a log from the log callback.
        /// </summary>
        /// <param name="message">Message.</param>
        /// <param name="stackTrace">Trace of where the message came from.</param>
        /// <param name="type">Type of message (error, exception, warning, assert).</param>
        void HandleLog(string message, string stackTrace, LogType type)
        {
            logs.Add(new Log
            {
                message = message,
                stackTrace = stackTrace,
                type = type,
            });


            TrimExcessLogs();
        }


        /// <summary>
        /// Removes old logs that exceed the maximum number allowed.
        /// </summary>
        void TrimExcessLogs()
        {
            if (!restrictLogCount)
            {
                return;
            }


            var amountToRemove = Mathf.Max(logs.Count - maxLogs, 0);


            if (amountToRemove == 0)
            {
                return;
            }


            logs.RemoveRange(0, amountToRemove);
        }
#endif
    }

}


随便写个C#代码,在Update中测试的。
[csharp]  view plain  copy
 print ?
  1. // Update is called once per frame  
  2.     void Update ()  
  3.     {  
  4.         //DebugConsole.Log(" test s");  
  5.         Debug.Log("Debug log  test");  
  6.         Console.WriteLine("this is Console Write line test ");  
  7.         ///  
  8.         //DebugConsole.instance.AddMessage("this is instance AddMessage test by cartzhang", "warning");  
  9.         //DebugConsole.Log("this is debug console log test cartzhang");  
  10.     }  

直接写在屏幕上的代码

  1.  using UnityEngine;  
  2.  using System.Collections;  
  3.   
  4.   
  5. public class DebugConsole : MonoBehaviour  
  6.  {  
  7. #if USE_DEBUGCONSOLE  
  8.     public GameObject DebugGui = null;             // The GUI that will be duplicated  
  9.     public Vector3 defaultGuiPosition = new Vector3(0.01F, 0.98F, 0F);  
  10.     public Vector3 defaultGuiScale = new Vector3(0.5F, 0.5F, 1F);  
  11.     public Color normal = Color.green;  
  12.     public Color warning = Color.yellow;  
  13.     public Color error = Color.red;  
  14.     public int maxMessages = 30;                   // The max number of messages displayed  
  15.     public float lineSpacing = 0.02F;              // The amount of space between lines  
  16.     public ArrayList messages = new ArrayList();  
  17.     public ArrayList guis = new ArrayList();  
  18.     public ArrayList colors = new ArrayList();  
  19.     public bool draggable = true;                  // Can the output be dragged around at runtime by default?   
  20.     public bool visible = true;                    // Does output show on screen by default or do we have to enable it with code?   
  21.     public bool pixelCorrect = false// set to be pixel Correct linespacing  
  22.     public static bool isVisible  
  23.     {                                        
  24.         get  
  25.         {  
  26.             return DebugConsole.instance.visible;  
  27.         }  
  28.    
  29.         set  
  30.         {  
  31.             DebugConsole.instance.visible = value;  
  32.             if (value == true)  
  33.             {  
  34.                 DebugConsole.instance.Display();  
  35.             }  
  36.             else if (value == false)  
  37.             {  
  38.                 DebugConsole.instance.ClearScreen();  
  39.             }  
  40.         }  
  41.     }  
  42.    
  43.     public static bool isDraggable  
  44.     {                                        
  45.         get  
  46.         {  
  47.             return DebugConsole.instance.draggable;  
  48.         }  
  49.    
  50.         set  
  51.         {  
  52.             DebugConsole.instance.draggable = value;  
  53.    
  54.         }  
  55.     }  
  56.    
  57.    
  58.     private static DebugConsole s_Instance = null;   // Our instance to allow this script to be called without a direct connection.  
  59.     public static DebugConsole instance  
  60.     {  
  61.         get  
  62.         {  
  63.             if (s_Instance == null)  
  64.             {  
  65.                 s_Instance = FindObjectOfType(typeof(DebugConsole)) as DebugConsole;  
  66.                 if (s_Instance == null)  
  67.                 {  
  68.                     GameObject console = new GameObject();  
  69.                     console.AddComponent<DebugConsole>();  
  70.                     console.name = "DebugConsoleController";  
  71.                     s_Instance = FindObjectOfType(typeof(DebugConsole)) as DebugConsole;  
  72.                     DebugConsole.instance.InitGuis();  
  73.                 }  
  74.    
  75.             }  
  76.    
  77.             return s_Instance;  
  78.         }  
  79.     }  
  80.    
  81.     void Awake()  
  82.     {  
  83.         s_Instance = this;  
  84.         InitGuis();  
  85.    
  86.     }  
  87.    
  88.     protected bool guisCreated = false;  
  89.     protected float screenHeight =-1;  
  90.     public void InitGuis()  
  91.     {  
  92.         float usedLineSpacing = lineSpacing;  
  93.         screenHeight = Screen.height;  
  94.         if(pixelCorrect)  
  95.             usedLineSpacing = 1.0F / screenHeight * usedLineSpacing;    
  96.    
  97.         if (guisCreated == false)  
  98.         {  
  99.             if (DebugGui == null)  // If an external GUIText is not set, provide the default GUIText  
  100.             {  
  101.                 DebugGui = new GameObject();  
  102.                 DebugGui.AddComponent<GUIText>();  
  103.                 DebugGui.name = "DebugGUI(0)";  
  104.                 DebugGui.transform.position = defaultGuiPosition;  
  105.                 DebugGui.transform.localScale = defaultGuiScale;  
  106.             }  
  107.    
  108.             // Create our GUI objects to our maxMessages count  
  109.             Vector3 position = DebugGui.transform.position;  
  110.             guis.Add(DebugGui);  
  111.             int x = 1;  
  112.    
  113.             while (x < maxMessages)  
  114.             {  
  115.                 position.y -= usedLineSpacing;  
  116.                 GameObject clone = null;  
  117.                 clone = (GameObject)Instantiate(DebugGui, position, transform.rotation);  
  118.                 clone.name = string.Format("DebugGUI({0})", x);  
  119.                 guis.Add(clone);  
  120.                 position = clone.transform.position;  
  121.                 x += 1;  
  122.             }  
  123.    
  124.             x = 0;  
  125.             while (x < guis.Count)  
  126.             {  
  127.                 GameObject temp = (GameObject)guis[x];  
  128.                 temp.transform.parent = DebugGui.transform;  
  129.                 x++;  
  130.             }  
  131.             guisCreated = true;  
  132.         } else {  
  133.             // we're called on a screensize change, so fiddle with sizes  
  134.             Vector3 position = DebugGui.transform.position;  
  135.             for(int x=0;x < guis.Count; x++)  
  136.             {  
  137.                 position.y -= usedLineSpacing;  
  138.                 GameObject temp = (GameObject)guis[x];  
  139.                 temp.transform.position= position;  
  140.             }         
  141.         }  
  142.     }  
  143.    
  144.    
  145.    
  146.     bool connectedToMouse = false;    
  147.     void Update()  
  148.     {  
  149.         // If we are visible and the screenHeight has changed, reset linespacing  
  150.         if (visible == true && screenHeight != Screen.height)  
  151.         {  
  152.             InitGuis();  
  153.         }  
  154.         if (draggable == true)  
  155.         {  
  156.             if (Input.GetMouseButtonDown(0))  
  157.             {  
  158.                 if (connectedToMouse == false && DebugGui.GetComponent<GUIText>().HitTest((Vector3)Input.mousePosition) == true)  
  159.                 {  
  160.                     connectedToMouse = true;  
  161.                 }  
  162.                 else if (connectedToMouse == true)  
  163.                 {  
  164.                     connectedToMouse = false;  
  165.                 }  
  166.    
  167.             }  
  168.    
  169.             if (connectedToMouse == true)  
  170.             {  
  171.                 float posX = DebugGui.transform.position.x;  
  172.                 float posY = DebugGui.transform.position.y;  
  173.                 posX = Input.mousePosition.x / Screen.width;  
  174.                 posY = Input.mousePosition.y / Screen.height;  
  175.                 DebugGui.transform.position = new Vector3(posX, posY, 0F);  
  176.             }  
  177.         }  
  178.    
  179.     }  
  180.     //+++++++++ INTERFACE FUNCTIONS ++++++++++++++++++++++++++++++++  
  181.     public static void Log(string message, string color)  
  182.     {  
  183.         DebugConsole.instance.AddMessage(message, color);  
  184.    
  185.     }  
  186.     //++++ OVERLOAD ++++  
  187.     public static void Log(string message)  
  188.     {  
  189.         DebugConsole.instance.AddMessage(message);  
  190.     }  
  191.    
  192.     public static void Clear()  
  193.     {  
  194.         DebugConsole.instance.ClearMessages();  
  195.     }  
  196.     //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++  
  197.    
  198.    
  199.     //---------- void AddMesage(string message, string color) ------  
  200.     //Adds a mesage to the list  
  201.     //--------------------------------------------------------------  
  202.    
  203.     public void AddMessage(string message, string color)  
  204.     {  
  205.         messages.Add(message);  
  206.         colors.Add(color);  
  207.         Display();  
  208.     }  
  209.     //++++++++++ OVERLOAD for AddMessage ++++++++++++++++++++++++++++  
  210.     // Overloads AddMessage to only require one argument(message)  
  211.     //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++  
  212.     public void AddMessage(string message)  
  213.     {  
  214.         messages.Add(message);  
  215.         colors.Add("normal");  
  216.         Display();  
  217.     }  
  218.    
  219.    
  220.     //----------- void ClearMessages() ------------------------------  
  221.     // Clears the messages from the screen and the lists  
  222.     //---------------------------------------------------------------  
  223.     public void ClearMessages()  
  224.     {  
  225.         messages.Clear();  
  226.         colors.Clear();  
  227.         ClearScreen();  
  228.     }  
  229.    
  230.    
  231.     //-------- void ClearScreen() ----------------------------------  
  232.     // Clears all output from all GUI objects  
  233.     //--------------------------------------------------------------  
  234.     void ClearScreen()  
  235.     {  
  236.         if (guis.Count < maxMessages)  
  237.         {  
  238.             //do nothing as we haven't created our guis yet  
  239.         }  
  240.         else  
  241.         {  
  242.             int x = 0;  
  243.             while (x < guis.Count)  
  244.             {  
  245.                 GameObject gui = (GameObject)guis[x];     
  246.                 gui.GetComponent<GUIText>().text = "";  
  247.                 //increment and loop  
  248.                 x += 1;  
  249.             }  
  250.         }  
  251.     }     
  252.    
  253.    
  254.     //---------- void Prune() ---------------------------------------  
  255.     // Prunes the array to fit within the maxMessages limit  
  256.     //---------------------------------------------------------------  
  257.     void Prune()  
  258.     {  
  259.         int diff;  
  260.         if (messages.Count > maxMessages)  
  261.         {  
  262.             if (messages.Count <= 0)  
  263.             {  
  264.                 diff = 0;  
  265.             }  
  266.             else  
  267.             {  
  268.                 diff = messages.Count - maxMessages;  
  269.             }  
  270.             messages.RemoveRange(0, (int)diff);  
  271.             colors.RemoveRange(0, (int)diff);  
  272.         }  
  273.    
  274.     }  
  275.    
  276.     //---------- void Display() -------------------------------------  
  277.     // Displays the list and handles coloring  
  278.     //---------------------------------------------------------------  
  279.     void Display()  
  280.     {  
  281.         //check if we are set to display  
  282.         if (visible == false)  
  283.         {  
  284.             ClearScreen();  
  285.         }  
  286.         else if (visible == true)  
  287.         {  
  288.    
  289.    
  290.             if (messages.Count > maxMessages)  
  291.             {  
  292.                 Prune();  
  293.             }  
  294.    
  295.             // Carry on with display  
  296.             int x = 0;  
  297.             if (guis.Count < maxMessages)  
  298.             {  
  299.                 //do nothing as we havent created our guis yet  
  300.             }  
  301.             else  
  302.             {  
  303.                 while (x < messages.Count)  
  304.                 {  
  305.                     GameObject gui = (GameObject)guis[x];     
  306.    
  307.                     //set our color  
  308.                     switch ((string)colors[x])  
  309.                     {  
  310.                         case "normal": gui.GetComponent<GUIText>().material.color = normal;  
  311.                             break;  
  312.                         case "warning": gui.GetComponent<GUIText>().material.color = warning;  
  313.                             break;  
  314.                         case "error": gui.GetComponent<GUIText>().material.color = error;  
  315.                             break;  
  316.                     }  
  317.    
  318.                     //now set the text for this element  
  319.                     gui.GetComponent<GUIText>().text = (string)messages[x];  
  320.    
  321.                     //increment and loop  
  322.                     x += 1;  
  323.                 }  
  324.             }  
  325.    
  326.         }  
  327.     }  
  328. #endif  
  329.    
  330.  }// End DebugConsole Class  

2.使用方法


[csharp]  view plain  copy
 print ?
  1. //DebugConsole.instance.AddMessage("this is instance AddMessage test by cartzhang", "warning");  
  2.        //DebugConsole.Log("this is debug console log test cartzhang");  


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

首先,输入的代码:
名字为ConsoleInput.cs
[csharp]  view plain  copy
 print ?
  1. using UnityEngine;  
  2. using System;  
  3. using System.Collections;  
  4. using System.Runtime.InteropServices;  
  5. using System.IO;  
  6.   
  7. namespace ConsoleTestWindows  
  8. {  
  9.     public class ConsoleInput  
  10.     {  
  11.         //public delegate void InputText( string strInput );  
  12.         public event System.Action<string> OnInputText;  
  13.         public string inputString;  
  14.   
  15.         public void ClearLine()  
  16.         {  
  17.             //System.Text.Encoding test = Console.InputEncoding;  
  18.             Console.CursorLeft = 0;  
  19.             Console.Write( new String( ' ', Console.BufferWidth ) );  
  20.             Console.CursorTop--;  
  21.             Console.CursorLeft = 0;  
  22.         }  
  23.   
  24.         public void RedrawInputLine()  
  25.         {  
  26.             if ( inputString.Length == 0 ) return;  
  27.   
  28.             if ( Console.CursorLeft > 0 )  
  29.                 ClearLine();  
  30.   
  31.             System.Console.ForegroundColor = ConsoleColor.Green;  
  32.             System.Console.Write( inputString );  
  33.         }  
  34.   
  35.         internal void OnBackspace()  
  36.         {  
  37.             if ( inputString.Length < 1 ) return;  
  38.   
  39.             inputString = inputString.Substring( 0, inputString.Length - 1 );  
  40.             RedrawInputLine();  
  41.         }  
  42.   
  43.         internal void OnEscape()  
  44.         {  
  45.             ClearLine();  
  46.             inputString = "";  
  47.         }  
  48.   
  49.         internal void OnEnter()  
  50.         {  
  51.             ClearLine();  
  52.             System.Console.ForegroundColor = ConsoleColor.Green;  
  53.             System.Console.WriteLine( "> " + inputString );  
  54.   
  55.             var strtext = inputString;  
  56.             inputString = "";  
  57.   
  58.             if ( OnInputText != null )  
  59.             {  
  60.                 OnInputText( strtext );  
  61.             }  
  62.         }  
  63.   
  64.         public void Update()  
  65.         {  
  66.             if ( !Console.KeyAvailable ) return;  
  67.             var key = Console.ReadKey();  
  68.   
  69.             if ( key.Key == ConsoleKey.Enter )  
  70.             {  
  71.                 OnEnter();  
  72.                 return;  
  73.             }  
  74.   
  75.             if ( key.Key == ConsoleKey.Backspace )  
  76.             {  
  77.                 OnBackspace();  
  78.                 return;  
  79.             }  
  80.   
  81.             if ( key.Key == ConsoleKey.Escape )  
  82.             {  
  83.                 OnEscape();  
  84.                 return;  
  85.             }  
  86.   
  87.             if ( key.KeyChar != '\u0000' )  
  88.             {  
  89.                 inputString += key.KeyChar;  
  90.                 RedrawInputLine();  
  91.                 return;  
  92.             }  
  93.         }  
  94.     }  
  95. }  

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

如下:
[csharp]  view plain  copy
 print ?
  1. using UnityEngine;  
  2. using System;  
  3. using System.Collections;  
  4. using System.Runtime.InteropServices;  
  5. using System.IO;  
  6.   
  7. namespace ConsoleTestWindows  
  8. {  
  9.     /// <summary>  
  10.     /// Creates a console window that actually works in Unity  
  11.     /// You should add a script that redirects output using Console.Write to write to it.  
  12.     /// </summary>  
  13.     public class ConsoleWindow  
  14.     {  
  15.         TextWriter oldOutput;  
  16.   
  17.         public void Initialize()  
  18.         {  
  19.             //  
  20.             // Attach to any existing consoles we have  
  21.             // failing that, create a new one.  
  22.             //  
  23.             if ( !AttachConsole( 0x0ffffffff ) )  
  24.             {  
  25.                 AllocConsole();  
  26.             }  
  27.   
  28.             oldOutput = Console.Out;  
  29.   
  30.             try  
  31.             {  
  32.                 IntPtr stdHandle = GetStdHandle( STD_OUTPUT_HANDLE );  
  33.                 Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle( stdHandle, true );  
  34.                 FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);  
  35.                 System.Text.Encoding encoding = System.Text.Encoding.ASCII;  
  36.                 StreamWriter standardOutput = new StreamWriter( fileStream, encoding );  
  37.                 standardOutput.AutoFlush = true;  
  38.                 Console.SetOut( standardOutput );  
  39.             }  
  40.             catch ( System.Exception e )  
  41.             {  
  42.                 Debug.Log( "Couldn't redirect output: " + e.Message );  
  43.             }  
  44.         }  
  45.   
  46.         public void Shutdown()  
  47.         {  
  48.             Console.SetOut( oldOutput );  
  49.             FreeConsole();  
  50.         }  
  51.   
  52.         public void SetTitle( string strName )  
  53.         {  
  54.             SetConsoleTitle( strName );  
  55.         }  
  56.   
  57.         private const int STD_OUTPUT_HANDLE = -11;  
  58.   
  59.         [DllImport( "kernel32.dll", SetLastError = true )]  
  60.         static extern bool AttachConsole( uint dwProcessId );  
  61.   
  62.         [DllImport( "kernel32.dll", SetLastError = true )]  
  63.         static extern bool AllocConsole();  
  64.   
  65.         [DllImport( "kernel32.dll", SetLastError = true )]  
  66.         static extern bool FreeConsole();  
  67.   
  68.         [DllImport( "kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall )]  
  69.         private static extern IntPtr GetStdHandle( int nStdHandle );  
  70.   
  71.         [DllImport( "kernel32.dll" )]  
  72.         static extern bool SetConsoleTitle( string lpConsoleTitle );  
  73.     }  
  74. }  

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


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

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


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

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



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

代码:UpgradeVSProject.cs

[csharp]  view plain  copy
 print ?
  1. //#define USE_UPGRADEVS  
  2. using UnityEngine;  
  3. using System.Collections;  
  4. using UnityEditor;  
  5. using System.IO;  
  6. using System.Text.RegularExpressions;  
  7.   
  8. class UpgradeVSProject : AssetPostprocessor  
  9. {  
  10. #if USE_UPGRADEVS  
  11.     private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)  
  12.     {  
  13.         string currentDir = Directory.GetCurrentDirectory();  
  14.         string[] slnFile = Directory.GetFiles(currentDir, "*.sln");  
  15.         string[] csprojFile = Directory.GetFiles(currentDir, "*.csproj");  
  16.   
  17.         bool hasChanged = false;  
  18.         if (slnFile != null)  
  19.         {  
  20.             for (int i = 0; i < slnFile.Length; i++)  
  21.             {  
  22.                 if (ReplaceInFile(slnFile[i], "Format Version 10.00""Format Version 11.00"))  
  23.                     hasChanged = true;  
  24.             }  
  25.         }  
  26.   
  27.         if (csprojFile != null)  
  28.         {  
  29.             for (int i = 0; i < csprojFile.Length; i++)  
  30.             {  
  31.                 if (ReplaceInFile(csprojFile[i], "ToolsVersion=\"3.5\"""ToolsVersion=\"4.0\""))  
  32.                     hasChanged = true;  
  33.   
  34.                 if (ReplaceInFile(csprojFile[i], "<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>""<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>"))  
  35.                     hasChanged = true;  
  36.             }  
  37.         }  
  38.   
  39.         if (hasChanged)  
  40.         {  
  41.             Debug.LogWarning("Project is now upgraded to Visual Studio 2010 Solution!");  
  42.         }  
  43.         else  
  44.         {  
  45.             Debug.Log("Project-version has not changed...");  
  46.         }  
  47.     }  
  48.   
  49.     static private bool ReplaceInFile(string filePath, string searchText, string replaceText)  
  50.     {  
  51.         StreamReader reader = new StreamReader(filePath);  
  52.         string content = reader.ReadToEnd();  
  53.         reader.Close();  
  54.   
  55.         if (content.IndexOf(searchText) != -1)  
  56.         {  
  57.             content = Regex.Replace(content, searchText, replaceText);  
  58.             StreamWriter writer = new StreamWriter(filePath);  
  59.             writer.Write(content);  
  60.             writer.Close();  
  61.   
  62.             return true;  
  63.         }  
  64.   
  65.         return false;  
  66.     }  
  67. #endif  
  68. }  

同样,我写了代码屏蔽的宏定义。使用的时候启用就可以了。
就可以自动升高版本到4.0上,当然你也可以修改代码来升高到其他版本的。

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

五、测试结果

我写了个几行的测试代码:
[csharp]  view plain  copy
 print ?
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class Tes : MonoBehaviour {  
  5.   
  6.     // Use this for initialization  
  7.     void Start () {  
  8.       
  9.     }  
  10.       
  11.     // Update is called once per frame  
  12.     void Update ()   
  13.     {  
  14.         if (Input.GetKey(KeyCode.A))  
  15.         {  
  16.             Debug.Log("this is debug log");  
  17.             System.Console.WriteLine("this is system console write line");  
  18.         }  
  19.       
  20.     }  
  21. }  

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值