DebugConsole

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
 
 
(27 intermediate revisions by 11 users not shown)
Line 4: Line 4:
 
[[Category: MonoBehaviour]]
 
[[Category: MonoBehaviour]]
 
Author: Jeremy Hollingsworth (jeremyace)
 
Author: Jeremy Hollingsworth (jeremyace)
 +
<BR>
 +
Modifications by:
 +
* Simon Waite (opless) 22 Feb 2006
 +
*Shinsuke Sugita (shinriyo) Dec 2015
 +
 
== Description ==
 
== Description ==
This script will control a guiText object to generate a scrolling console-like debug feeback pane.  Allows you to set one of three colors (normal, warning, error) to each line to get more feedback.
+
This script will create a scrolling debug console.  Allows you to set one of three colors (normal, warning, error) to each line to get more feedback and is mouse draggable at runtime.
  
 
== Usage ==
 
== Usage ==
<b>This C# script _must_ be placed in the Standard Assets folder to be called from Jscript.</b>
+
Drop the DebugConsole script into your Standard Assets folder (This is a <b>requirement</b>).  It is now fully usable.
 
+
<BR><b>First create a new guiText (GameObject->Create Other->Text).</b> This guiText will be duplicated and moved by the script to form your debug output, so set it up as you want the individual output lines to appear.
+
<BR>-> Make sure the Text field of the guiText is blank.
+
<BR>-> Make sure you set a material (the orange font material) as the code will be modifying the color property.
+
<BR>-> Make sure you set the position of this object as where you want the first line of output to be (code duplicate down).
+
<BR>-> I recommend you cut the scale down so you can fit more lines in the output.
+
  
<BR><b>Now create a new blank GameObject (GameObject->Create Empty) and then drag the DebugGUIController.cs script to it.</b>
+
If you want to change the default settings (like colors, or change the GUIText object), then create an empty GameObject and drag this script onto it from the standard assets folder. You now have access to all of the default settings in the inspector.  The settings are explained below.
  
 
<BR><b>Settings:</b>
 
<BR><b>Settings:</b>
<BR>->Debug GUI : Drag the guiText you created here.
+
* <b>Debug GUI</b> : Drag the guiText you created here if you wish to override the default.
<BR>->The three colors are for normal, warning, and error.  Set to whatever you like or leave alone.
+
* <b>defaultGuiPosition</b> : A vector for the starting position of the first line of output.  If you provide your own GUIText then it's position overrides this property.
<BR>->Max messages : How many message lines we will put on the screen at once.  This number depends on the size of your guiText.
+
* <b>defaultGuiScale</b> : A vector for the scale of the individual lines.  Again, this is overridden if you provide your own GUIText.
<BR>->Line Spacing : A float for how far down we will move each new line.  Again, this depends on the size of your guiText.
+
* <b>The three colors</b> : are for normal, warning, and error.  Set to whatever you like or leave alone.
<BR>->Show On Screen : The default setting for visibility of the debug output.  If set to false (unchecked), you can send data but it wont show until you tell it to, if set to true (checked) it will show all debug output until you tell it not to.
+
* <b>Max messages</b> : How many message lines we will put on the screen at once.
 +
* <b>Line Spacing</b> : A float for how far down we will move each new line.
 +
* <b>Draggable</b> : True means you can drag the output around with the mouse at runtime, false means position is locked from mouse inputTo drag output at runtime, click once on the uppermost output line to connect it to the mouse, then move to where you want the output displayed and click the mouse again to release it.
 +
* <b>Visible</b> : The default setting for visibility of the debug output.  If set to false (unchecked), you can send data but it wont show until you tell it to, if set to true (checked) it will show all debug output until you tell it not to.
 +
* <b>PixelCorrect</b> : If set to <i>true</i> and LineSpacing to be on-screen pixels or not, very much like the GUIText property of the same name. Default: <i>false</i> LineSpacing will be in screen coordinates (0.0 - 1.0)
  
<BR>The setup is done!
+
<BR><b>Using the DebugConsole script from your scripts:</b>
 +
<BR>To call the DebugConsole script from your scripts, just type:
  
<BR><b>Using the Debug script from your scripts:</b>
+
<BR><b>DebugConsole</b>.<i>someFunction()</i>
<BR>To call the DebugGUIController script from your scripts, just type:
+
<BR>DebugGUIController.instance.<i>someFunction()</i>
+
  
 
<BR>Replace <i>someFunction()</i> with any of the following:
 
<BR>Replace <i>someFunction()</i> with any of the following:
  
<BR><b>AddMessage</b>(<b>string</b> <i>message</i>, <b>string</b> <i>color</i>)
+
<BR><b>Log</b> (<b>string</b> <i>message</i>, <b>string</b> <i>color</i>)
<BR>->Adds a message to the list.  The color is a string either <i>"normal", "warning" or "error"</i>.  The color argument is optional and if omitted, the color will default to "normal".
+
* Adds a message to the list.  The color is a string either <i>"normal", "warning" or "error"</i>.  The color argument is optional and if omitted, the color will default to "normal".
  
<BR><b>ClearMessages()</b>
+
<BR><b>Clear()</b>
<BR>->Clears all of the messages from the list and the screen.
+
* Clears all of the messages from the list and the screen.
  
<BR><b>Hide()</b>
+
<BR><B>To toggle the visibility use:</b>
<BR>->Hides the display of the output. Does not reset the contents of the list (same as setting Show On Screen to false in the inspector)
+
<BR><b>isVisible</b> (true, false)
 +
*  The property to set the visiblility of the debug output. This property _not_ clear the message list, just hides it. You need to use the Clear() method to clear the list.
  
<BR><b>Show()</b>
+
<BR><B>To toggle the mouse drag functionality use:</b>
<BR>->Shows the previously hidden display.
+
<BR><b>isDraggable</b> (true, false)
  
 
<BR>So for a simple example, to add hello world in warning color (yellow), we type:
 
<BR>So for a simple example, to add hello world in warning color (yellow), we type:
DebugGUIController.instance.AddMessage("hello world", "warning");
+
DebugConsole.Log("hello world", "warning");
  
 +
<BR>To hide the output we type:
 +
DebugConsole.isVisible = false;
 +
 +
== C# - DebugConsole.cs ==
 +
The script _must_ be named DebugConsole.cs
 +
 +
<syntaxhighlight lang="csharp">
 +
/*==== DebugConsole.cs ====================================================
 +
* Class for handling multi-line, multi-color debugging messages.
 +
* Original Author: Jeremy Hollingsworth
 +
* Based On: Version 1.2.1 Mar 02, 2006
 +
*
 +
* Modified: Simon Waite
 +
* Date: 22 Feb 2007
 +
*
 +
* Modified: Shinsuke Sugita
 +
* Date: 1 Dec 2015
 +
*
 +
* Modification to original script to allow pixel-correct line spacing
 +
*
 +
* Setting the boolean pixelCorrect changes the units in lineSpacing property
 +
* to pixels, so you have a pixel correct gui font in your console.
 +
*
 +
* It also checks every frame if the screen is resized to make sure the
 +
* line spacing is correct (To see this; drag and let go in the editor
 +
* and the text spacing will snap back)
 +
*
 +
* USAGE:
 +
* ::Drop in your standard assets folder (if you want to change any of the
 +
* default settings in the inspector, create an empty GameObject and attach
 +
* this script to it from you standard assets folder.  That will provide
 +
* access to the default settings in the inspector)
 +
*
 +
* ::To use, call DebugConsole.functionOrProperty() where
 +
* functionOrProperty = one of the following:
 +
*
 +
* -Log(string message, string color)  Adds "message" to the list with the
 +
* "color" color. Color is optional and can be any of the following: "error",
 +
* "warning", or "normal".  Default is normal.
 +
*
 +
* Clear() Clears all messages
 +
*
 +
* isVisible (true,false)  Toggles the visibility of the output.  Does _not_
 +
* clear the messages.
 +
*
 +
* isDraggable (true, false)  Toggles mouse drag functionality
 +
* =========================================================================*/
  
  
== C# - DebugGUIController.cs ==
 
The script _must_ be named DebugGUIController.cs
 
<csharp>
 
 
using UnityEngine;
 
using UnityEngine;
 
using System.Collections;
 
using System.Collections;
  
  
public class DebugGUIController : MonoBehaviour {
+
public class DebugConsole : MonoBehaviour
 
+
{
public GameObject DebugGui = null;            // The GUI that will be duplicated
+
public GameObject DebugGui = null;            // The GUI that will be duplicated
public Color normal = Color.green;
+
public Vector3 defaultGuiPosition = new Vector3(0.01F, 0.98F, 0F);
public Color warning = Color.yellow;  
+
public Vector3 defaultGuiScale = new Vector3(0.5F, 0.5F, 1F);
public Color error = Color.red;
+
public Color normal = Color.green;
public int maxMessages = 7;                  // The max number of messages displayed
+
public Color warning = Color.yellow;
public float lineSpacing = 0.02F;              // The amount of space between lines
+
public Color error = Color.red;
public ArrayList messages = new ArrayList(); // The messages array
+
public int maxMessages = 30;                  // The max number of messages displayed
public ArrayList names = new ArrayList();     // The GUI names array.  This holds the names of our duplicated GUIs (might not be needed)
+
public float lineSpacing = 0.02F;              // The amount of space between lines
public ArrayList colors = new ArrayList();   // The array that holds the user selection of color for each message. normal, warning, error.
+
public ArrayList messages = new ArrayList();
public ArrayList pruneArray = new ArrayList();
+
public ArrayList guis = new ArrayList();
public bool showOnScreen = true;             // Does the output actually get displayed on screen or not?
+
public ArrayList colors = new ArrayList();
 
+
public bool draggable = true;                 // Can the output be dragged around at runtime by default?
 
+
public bool visible = true;                   // Does output show on screen by default or do we have to enable it with code?  
// s_Instance is used to cache the instance found in the scene so we don't have to look it up every time.
+
public bool pixelCorrect = false; // set to be pixel Correct linespacing
    private static DebugGUIController s_Instance = null;
+
public static bool isVisible
+
{                                     
    // This defines a static instance property that attempts to find the manager object in the scene and
+
get
    // returns it to the caller.
+
{
    public static DebugGUIController instance {
+
return DebugConsole.instance.visible;
        get {
+
}
            if (s_Instance == null) {
+
                // This is where the magic happens.
+
set
                //  FindObjectOfType(...) returns the first AManager object in the scene.
+
{
                s_Instance = FindObjectOfType(typeof (DebugGUIController)) as DebugGUIController;
+
DebugConsole.instance.visible = value;
                if (s_Instance == null)
+
if (value == true)
                    Debug.Log ("Could not locate a DebugGUIController object. You have to have exactly one DebugGUIController in the scene.");
+
{
            }
+
DebugConsole.instance.Display();
           
+
}
            return s_Instance;
+
else if (value == false)
        }
+
{
    }
+
DebugConsole.instance.ClearScreen();
   
+
}
    void Awake() {
+
}
        s_Instance = this;
+
}
    }
+
 
+
public static bool isDraggable
public void Start()
+
{                                     
{  // Create our GUI objects to our maxMessages count
+
get
Vector3 position = new Vector3(0.01F, DebugGui.transform.position.y, 0F);
+
{
  int x = 0;
+
return DebugConsole.instance.draggable;
  while(x < maxMessages)
+
}
    {
+
       
+
set
        position.y -= lineSpacing; //new position moved down from parent
+
{
        Object clone = null;
+
DebugConsole.instance.draggable = value;
        clone = Instantiate(DebugGui, position, transform.rotation);
+
        string name = "DebugGui(" + x + ")";   // Add the current loop number to the DebugGui() name string
+
}
        names.Add(name);   // add the name to our name array (might have to change this to work on a per-element basis)  
+
}
        clone.name = name;  // Set the name of our newly instantiated GUI object.
+
        x+=1;  
+
    }
+
private static DebugConsole s_Instance = null;   // Our instance to allow this script to be called without a direct connection.
 
+
public static DebugConsole instance
}  
+
{
 
+
get
 
+
{
 
+
if (s_Instance == null)
 
+
{
    //---------- void AddMesage(string message, string color) ------
+
s_Instance = FindObjectOfType(typeof(DebugConsole)) as DebugConsole;
    //Adds a mesage to the list
+
if (s_Instance == null)
    //--------------------------------------------------------------
+
{
 +
GameObject console = new GameObject();
 +
console.AddComponent<DebugConsole>();
 +
console.name = "DebugConsoleController";
 +
s_Instance = FindObjectOfType(typeof(DebugConsole)) as DebugConsole;
 +
DebugConsole.instance.InitGuis();
 +
}
 +
 +
}
 +
 +
return s_Instance;
 +
}
 +
}
 +
 +
void Awake()
 +
{
 +
s_Instance = this;
 +
InitGuis();
 +
 +
}
 +
 +
protected bool guisCreated = false;
 +
protected float screenHeight =-1;
 +
public void InitGuis()
 +
{
 +
float usedLineSpacing = lineSpacing;
 +
screenHeight = Screen.height;
 +
if(pixelCorrect)
 +
usedLineSpacing = 1.0F / screenHeight * usedLineSpacing;  
 +
 +
if (guisCreated == false)
 +
{
 +
if (DebugGui == null)  // If an external GUIText is not set, provide the default GUIText
 +
{
 +
DebugGui = new GameObject();
 +
DebugGui.AddComponent<GUIText>();
 +
DebugGui.name = "DebugGUI(0)";
 +
DebugGui.transform.position = defaultGuiPosition;
 +
DebugGui.transform.localScale = defaultGuiScale;
 +
}
 +
 +
// Create our GUI objects to our maxMessages count
 +
Vector3 position = DebugGui.transform.position;
 +
guis.Add(DebugGui);
 +
int x = 1;
 +
 +
while (x < maxMessages)
 +
{
 +
position.y -= usedLineSpacing;
 +
GameObject clone = null;
 +
clone = (GameObject)Instantiate(DebugGui, position, transform.rotation);
 +
clone.name = string.Format("DebugGUI({0})", x);
 +
guis.Add(clone);
 +
position = clone.transform.position;
 +
x += 1;
 +
}
 +
 +
x = 0;
 +
while (x < guis.Count)
 +
{
 +
GameObject temp = (GameObject)guis[x];
 +
temp.transform.parent = DebugGui.transform;
 +
x++;
 +
}
 +
guisCreated = true;
 +
} else {
 +
// we're called on a screensize change, so fiddle with sizes
 +
Vector3 position = DebugGui.transform.position;
 +
for(int x=0;x < guis.Count; x++)
 +
{
 +
position.y -= usedLineSpacing;
 +
GameObject temp = (GameObject)guis[x];
 +
temp.transform.position= position;
 +
}   
 +
}
 +
}
 +
 +
 +
 +
bool connectedToMouse = false;   
 +
void Update()
 +
{
 +
// If we are visible and the screenHeight has changed, reset linespacing
 +
if (visible == true && screenHeight != Screen.height)
 +
{
 +
InitGuis();
 +
}
 +
if (draggable == true)
 +
{
 +
if (Input.GetMouseButtonDown(0))
 +
{
 +
if (connectedToMouse == false && DebugGui.GetComponent<GUIText>().HitTest((Vector3)Input.mousePosition) == true)
 +
{
 +
connectedToMouse = true;
 +
}
 +
else if (connectedToMouse == true)
 +
{
 +
connectedToMouse = false;
 +
}
 +
 +
}
 +
 +
if (connectedToMouse == true)
 +
{
 +
float posX = DebugGui.transform.position.x;
 +
float posY = DebugGui.transform.position.y;
 +
posX = Input.mousePosition.x / Screen.width;
 +
posY = Input.mousePosition.y / Screen.height;
 +
DebugGui.transform.position = new Vector3(posX, posY, 0F);
 +
}
 +
}
 +
 +
}
 +
//+++++++++ INTERFACE FUNCTIONS ++++++++++++++++++++++++++++++++
 +
public static void Log(string message, string color)
 +
{
 +
DebugConsole.instance.AddMessage(message, color);
 +
 +
}
 +
//++++ OVERLOAD ++++
 +
public static void Log(string message)
 +
{
 +
DebugConsole.instance.AddMessage(message);
 +
}
 +
 +
public static void Clear()
 +
{
 +
DebugConsole.instance.ClearMessages();
 +
}
 +
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 +
 +
 +
//---------- void AddMesage(string message, string color) ------
 +
//Adds a mesage to the list
 +
//--------------------------------------------------------------
 
 
 
public void AddMessage(string message, string color)
 
public void AddMessage(string message, string color)
 
{
 
{
  messages.Add(message);
+
messages.Add(message);
  colors.Add(color); // TODO: make sure this gets set to a default value if empty
+
colors.Add(color);
  Display();
+
Display();
 
}
 
}
 
//++++++++++ OVERLOAD for AddMessage ++++++++++++++++++++++++++++
 
//++++++++++ OVERLOAD for AddMessage ++++++++++++++++++++++++++++
Line 131: Line 312:
 
public void AddMessage(string message)
 
public void AddMessage(string message)
 
{
 
{
  messages.Add(message);
+
messages.Add(message);
  colors.Add("normal");
+
colors.Add("normal");
  Display();
+
Display();
    }
+
}
 
+
 
 
 
 
    //----------- void ClearMessages() ------------------------------
+
//----------- void ClearMessages() ------------------------------
    // Clears the messages from the screen and the lists
+
// Clears the messages from the screen and the lists
    //---------------------------------------------------------------
+
//---------------------------------------------------------------
    public void ClearMessages()
+
public void ClearMessages()
    {
+
{
        messages.Clear();
+
messages.Clear();
        colors.Clear();
+
colors.Clear();
        ClearScreen();
+
ClearScreen();
    }
+
}
   
+
   
+
    //--------- void Hide() -----------------------------------------
+
//-------- void ClearScreen() ----------------------------------
    // Hides the display with a variable, but does NOT clear arrays
+
// Clears all output from all GUI objects
    //---------------------------------------------------------------
+
//--------------------------------------------------------------
    public void Hide()
+
void ClearScreen()
    {
+
{
        showOnScreen = false;
+
if (guis.Count < maxMessages)
        ClearScreen();
+
{
    }
+
//do nothing as we haven't created our guis yet
   
+
}
   
+
else
    //--------- void Show() ----------------------------------------
+
{
    // Shows the hidden display on the screen
+
int x = 0;
    //--------------------------------------------------------------
+
while (x < guis.Count)
    public void Show()
+
{
    {
+
GameObject gui = (GameObject)guis[x];   
        showOnScreen = true;
+
gui.GetComponent<GUIText>().text = "";
        Display();
+
//increment and loop
    }
+
x += 1;
   
+
}
   
+
}
 
+
}  
    //-------- void ClearScreen() ----------------------------------
+
    // Clears all output from all GUI objects
+
    //--------------------------------------------------------------
+
//---------- void Prune() ---------------------------------------
    void ClearScreen()
+
// Prunes the array to fit within the maxMessages limit
    {
+
//---------------------------------------------------------------
        int x = 0;
+
void Prune()
        while (x < names.Count)
+
{
        {
+
int diff;
            GameObject gui = GameObject.Find((string)names[x])//find our gui object
+
if (messages.Count > maxMessages)
            gui.guiText.text = "";
+
{
            //increment and loop
+
if (messages.Count <= 0)
            x += 1;
+
{
         
+
diff = 0;
        }//end loop
+
}
    }
+
else
 
+
{
   
+
diff = messages.Count - maxMessages;
   
+
}
    //---------- void Prune() ---------------------------------------
+
messages.RemoveRange(0, (int)diff);
    // Prunes the array to fit within the maxMessages limit
+
colors.RemoveRange(0, (int)diff);
    //---------------------------------------------------------------
+
}
    void Prune()
+
    {
+
}
    int diff;
+
        if (messages.Count > maxMessages)
+
//---------- void Display() -------------------------------------
        {
+
// Displays the list and handles coloring
          if (messages.Count <= 0)
+
//---------------------------------------------------------------
          {
+
void Display()
            diff = 0;
+
{
          }
+
//check if we are set to display
          else
+
if (visible == false)
          {
+
{
            diff = messages.Count - maxMessages;
+
ClearScreen();
          }
+
}
          messages.RemoveRange(0, (int)diff);
+
else if (visible == true)
          colors.RemoveRange(0, (int)diff);
+
{
        }
+
   
+
    }
+
if (messages.Count > maxMessages)
   
+
{
    //---------- void Display() -------------------------------------
+
Prune();
    // Displays the list and handles coloring
+
}
    //---------------------------------------------------------------
+
    public void Display()
+
// Carry on with display
    {
+
int x = 0;
        //check if we are set to display
+
if (guis.Count < maxMessages)
        if (showOnScreen == false)
+
{
        {
+
//do nothing as we havent created our guis yet
          ClearScreen();
+
}
        }
+
else
        else  
+
{
        {
+
while (x < messages.Count)
            if (messages.Count > maxMessages)
+
{
            {
+
GameObject gui = (GameObject)guis[x];   
              Prune();
+
            }          
+
//set our color
       
+
switch ((string)colors[x])
        // Carry on with display
+
{
               
+
case "normal": gui.GetComponent<GUIText>().material.color = normal;
        int x = 0;
+
break;
        while (x < messages.Count)
+
case "warning": gui.GetComponent<GUIText>().material.color = warning;
        {
+
break;
     
+
case "error": gui.GetComponent<GUIText>().material.color = error;
            GameObject gui = GameObject.Find((string)names[x])//find our gui object
+
break;
            //set our color
+
}
           
+
            switch ((string) colors[x])
+
//now set the text for this element
            {
+
gui.GetComponent<GUIText>().text = (string)messages[x];
                case "normal": gui.guiText.material.color = normal;
+
                break;
+
//increment and loop
                case "warning": gui.guiText.material.color = warning;
+
x += 1;
                break;
+
}
                case "error": gui.guiText.material.color = error;
+
}
                break;
+
            }
+
}
            //now set the text for this element
+
}
            gui.guiText.text = (string)messages[x];
+
           
+
            //increment and loop
+
}// End DebugConsole Class
            x += 1;
+
</syntaxhighlight>
         
+
        }//end loop
+
           
+
       
+
       
+
        }//end display check
+
   
+
    }  
+
 
+
}// End Class
+
 
+
</csharp>
+

Latest revision as of 03:38, 1 December 2015

Author: Jeremy Hollingsworth (jeremyace)
Modifications by:

  • Simon Waite (opless) 22 Feb 2006
  • Shinsuke Sugita (shinriyo) Dec 2015

[edit] Description

This script will create a scrolling debug console. Allows you to set one of three colors (normal, warning, error) to each line to get more feedback and is mouse draggable at runtime.

[edit] Usage

Drop the DebugConsole script into your Standard Assets folder (This is a requirement). It is now fully usable.

If you want to change the default settings (like colors, or change the GUIText object), then create an empty GameObject and drag this script onto it from the standard assets folder. You now have access to all of the default settings in the inspector. The settings are explained below.


Settings:

  • Debug GUI : Drag the guiText you created here if you wish to override the default.
  • defaultGuiPosition : A vector for the starting position of the first line of output. If you provide your own GUIText then it's position overrides this property.
  • defaultGuiScale : A vector for the scale of the individual lines. Again, this is overridden if you provide your own GUIText.
  • The three colors : are for normal, warning, and error. Set to whatever you like or leave alone.
  • Max messages : How many message lines we will put on the screen at once.
  • Line Spacing : A float for how far down we will move each new line.
  • Draggable : True means you can drag the output around with the mouse at runtime, false means position is locked from mouse input. To drag output at runtime, click once on the uppermost output line to connect it to the mouse, then move to where you want the output displayed and click the mouse again to release it.
  • Visible : The default setting for visibility of the debug output. If set to false (unchecked), you can send data but it wont show until you tell it to, if set to true (checked) it will show all debug output until you tell it not to.
  • PixelCorrect : If set to true and LineSpacing to be on-screen pixels or not, very much like the GUIText property of the same name. Default: false LineSpacing will be in screen coordinates (0.0 - 1.0)


Using the DebugConsole script from your scripts:
To call the DebugConsole script from your scripts, just type:


DebugConsole.someFunction()


Replace someFunction() with any of the following:


Log (string message, string color)

  • Adds a message to the list. The color is a string either "normal", "warning" or "error". The color argument is optional and if omitted, the color will default to "normal".


Clear()

  • Clears all of the messages from the list and the screen.


To toggle the visibility use:
isVisible (true, false)

  • The property to set the visiblility of the debug output. This property _not_ clear the message list, just hides it. You need to use the Clear() method to clear the list.


To toggle the mouse drag functionality use:
isDraggable (true, false)


So for a simple example, to add hello world in warning color (yellow), we type: DebugConsole.Log("hello world", "warning");


To hide the output we type: DebugConsole.isVisible = false;

[edit] C# - DebugConsole.cs

The script _must_ be named DebugConsole.cs

/*==== DebugConsole.cs ====================================================
 * Class for handling multi-line, multi-color debugging messages.
 * Original Author: Jeremy Hollingsworth
 * Based On: Version 1.2.1 Mar 02, 2006
 * 
 * Modified: Simon Waite
 * Date: 22 Feb 2007
 *
 * Modified: Shinsuke Sugita
 * Date: 1 Dec 2015
 * 
 * Modification to original script to allow pixel-correct line spacing
 *
 * Setting the boolean pixelCorrect changes the units in lineSpacing property
 * to pixels, so you have a pixel correct gui font in your console.
 *
 * It also checks every frame if the screen is resized to make sure the 
 * line spacing is correct (To see this; drag and let go in the editor 
 * and the text spacing will snap back)
 *
 * USAGE:
 * ::Drop in your standard assets folder (if you want to change any of the
 * default settings in the inspector, create an empty GameObject and attach
 * this script to it from you standard assets folder.  That will provide
 * access to the default settings in the inspector)
 * 
 * ::To use, call DebugConsole.functionOrProperty() where 
 * functionOrProperty = one of the following:
 * 
 * -Log(string message, string color)  Adds "message" to the list with the
 * "color" color. Color is optional and can be any of the following: "error",
 * "warning", or "normal".  Default is normal.
 * 
 * Clear() Clears all messages
 * 
 * isVisible (true,false)  Toggles the visibility of the output.  Does _not_
 * clear the messages.
 * 
 * isDraggable (true, false)  Toggles mouse drag functionality
 * =========================================================================*/
 
 
using UnityEngine;
using System.Collections;
 
 
public class DebugConsole : MonoBehaviour
{
	public GameObject DebugGui = null;             // The GUI that will be duplicated
	public Vector3 defaultGuiPosition = new Vector3(0.01F, 0.98F, 0F);
	public Vector3 defaultGuiScale = new Vector3(0.5F, 0.5F, 1F);
	public Color normal = Color.green;
	public Color warning = Color.yellow;
	public Color error = Color.red;
	public int maxMessages = 30;                   // The max number of messages displayed
	public float lineSpacing = 0.02F;              // The amount of space between lines
	public ArrayList messages = new ArrayList();
	public ArrayList guis = new ArrayList();
	public ArrayList colors = new ArrayList();
	public bool draggable = true;                  // Can the output be dragged around at runtime by default? 
	public bool visible = true;                    // Does output show on screen by default or do we have to enable it with code? 
	public bool pixelCorrect = false; // set to be pixel Correct linespacing
	public static bool isVisible
	{                                      
		get
		{
			return DebugConsole.instance.visible;
		}
 
		set
		{
			DebugConsole.instance.visible = value;
			if (value == true)
			{
				DebugConsole.instance.Display();
			}
			else if (value == false)
			{
				DebugConsole.instance.ClearScreen();
			}
		}
	}
 
	public static bool isDraggable
	{                                      
		get
		{
			return DebugConsole.instance.draggable;
		}
 
		set
		{
			DebugConsole.instance.draggable = value;
 
		}
	}
 
 
	private static DebugConsole s_Instance = null;   // Our instance to allow this script to be called without a direct connection.
	public static DebugConsole instance
	{
		get
		{
			if (s_Instance == null)
			{
				s_Instance = FindObjectOfType(typeof(DebugConsole)) as DebugConsole;
				if (s_Instance == null)
				{
					GameObject console = new GameObject();
					console.AddComponent<DebugConsole>();
					console.name = "DebugConsoleController";
					s_Instance = FindObjectOfType(typeof(DebugConsole)) as DebugConsole;
					DebugConsole.instance.InitGuis();
				}
 
			}
 
			return s_Instance;
		}
	}
 
	void Awake()
	{
		s_Instance = this;
		InitGuis();
 
	}
 
	protected bool guisCreated = false;
	protected float screenHeight =-1;
	public void InitGuis()
	{
		float usedLineSpacing = lineSpacing;
		screenHeight = Screen.height;
		if(pixelCorrect)
			usedLineSpacing = 1.0F / screenHeight * usedLineSpacing;  
 
		if (guisCreated == false)
		{
			if (DebugGui == null)  // If an external GUIText is not set, provide the default GUIText
			{
				DebugGui = new GameObject();
				DebugGui.AddComponent<GUIText>();
				DebugGui.name = "DebugGUI(0)";
				DebugGui.transform.position = defaultGuiPosition;
				DebugGui.transform.localScale = defaultGuiScale;
			}
 
			// Create our GUI objects to our maxMessages count
			Vector3 position = DebugGui.transform.position;
			guis.Add(DebugGui);
			int x = 1;
 
			while (x < maxMessages)
			{
				position.y -= usedLineSpacing;
				GameObject clone = null;
				clone = (GameObject)Instantiate(DebugGui, position, transform.rotation);
				clone.name = string.Format("DebugGUI({0})", x);
				guis.Add(clone);
				position = clone.transform.position;
				x += 1;
			}
 
			x = 0;
			while (x < guis.Count)
			{
				GameObject temp = (GameObject)guis[x];
				temp.transform.parent = DebugGui.transform;
				x++;
			}
			guisCreated = true;
		} else {
			// we're called on a screensize change, so fiddle with sizes
			Vector3 position = DebugGui.transform.position;
			for(int x=0;x < guis.Count; x++)
			{
				position.y -= usedLineSpacing;
				GameObject temp = (GameObject)guis[x];
				temp.transform.position= position;
			}    	
		}
	}
 
 
 
	bool connectedToMouse = false;  
	void Update()
	{
		// If we are visible and the screenHeight has changed, reset linespacing
		if (visible == true && screenHeight != Screen.height)
		{
			InitGuis();
		}
		if (draggable == true)
		{
			if (Input.GetMouseButtonDown(0))
			{
				if (connectedToMouse == false && DebugGui.GetComponent<GUIText>().HitTest((Vector3)Input.mousePosition) == true)
				{
					connectedToMouse = true;
				}
				else if (connectedToMouse == true)
				{
					connectedToMouse = false;
				}
 
			}
 
			if (connectedToMouse == true)
			{
				float posX = DebugGui.transform.position.x;
				float posY = DebugGui.transform.position.y;
				posX = Input.mousePosition.x / Screen.width;
				posY = Input.mousePosition.y / Screen.height;
				DebugGui.transform.position = new Vector3(posX, posY, 0F);
			}
		}
 
	}
	//+++++++++ INTERFACE FUNCTIONS ++++++++++++++++++++++++++++++++
	public static void Log(string message, string color)
	{
		DebugConsole.instance.AddMessage(message, color);
 
	}
	//++++ OVERLOAD ++++
	public static void Log(string message)
	{
		DebugConsole.instance.AddMessage(message);
	}
 
	public static void Clear()
	{
		DebugConsole.instance.ClearMessages();
	}
	//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 
	//---------- void AddMesage(string message, string color) ------
	//Adds a mesage to the list
	//--------------------------------------------------------------
 
	public void AddMessage(string message, string color)
	{
		messages.Add(message);
		colors.Add(color);
		Display();
	}
	//++++++++++ OVERLOAD for AddMessage ++++++++++++++++++++++++++++
	// Overloads AddMessage to only require one argument(message)
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	public void AddMessage(string message)
	{
		messages.Add(message);
		colors.Add("normal");
		Display();
	}
 
 
	//----------- void ClearMessages() ------------------------------
	// Clears the messages from the screen and the lists
	//---------------------------------------------------------------
	public void ClearMessages()
	{
		messages.Clear();
		colors.Clear();
		ClearScreen();
	}
 
 
	//-------- void ClearScreen() ----------------------------------
	// Clears all output from all GUI objects
	//--------------------------------------------------------------
	void ClearScreen()
	{
		if (guis.Count < maxMessages)
		{
			//do nothing as we haven't created our guis yet
		}
		else
		{
			int x = 0;
			while (x < guis.Count)
			{
				GameObject gui = (GameObject)guis[x];   
				gui.GetComponent<GUIText>().text = "";
				//increment and loop
				x += 1;
			}
		}
	}   
 
 
	//---------- void Prune() ---------------------------------------
	// Prunes the array to fit within the maxMessages limit
	//---------------------------------------------------------------
	void Prune()
	{
		int diff;
		if (messages.Count > maxMessages)
		{
			if (messages.Count <= 0)
			{
				diff = 0;
			}
			else
			{
				diff = messages.Count - maxMessages;
			}
			messages.RemoveRange(0, (int)diff);
			colors.RemoveRange(0, (int)diff);
		}
 
	}
 
	//---------- void Display() -------------------------------------
	// Displays the list and handles coloring
	//---------------------------------------------------------------
	void Display()
	{
		//check if we are set to display
		if (visible == false)
		{
			ClearScreen();
		}
		else if (visible == true)
		{
 
 
			if (messages.Count > maxMessages)
			{
				Prune();
			}
 
			// Carry on with display
			int x = 0;
			if (guis.Count < maxMessages)
			{
				//do nothing as we havent created our guis yet
			}
			else
			{
				while (x < messages.Count)
				{
					GameObject gui = (GameObject)guis[x];   
 
					//set our color
					switch ((string)colors[x])
					{
					case "normal": gui.GetComponent<GUIText>().material.color = normal;
						break;
					case "warning": gui.GetComponent<GUIText>().material.color = warning;
						break;
					case "error": gui.GetComponent<GUIText>().material.color = error;
						break;
					}
 
					//now set the text for this element
					gui.GetComponent<GUIText>().text = (string)messages[x];
 
					//increment and loop
					x += 1;
				}
			}
 
		}
	}
 
 
}// End DebugConsole Class
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox