Search Unity

I'm making a GUI Chatbox for all! (Please help lol)

Discussion in 'Immediate Mode GUI (IMGUI)' started by MythStrott, Aug 29, 2010.

  1. MythStrott

    MythStrott

    Joined:
    Jul 2, 2010
    Posts:
    64
    I have finished the script!

    It is fully-functional. I give anybody permission to use it in their projects. Please post any useful edits you make to it.

    Thanks

    Code (csharp):
    1. //This script was originally made by MythStrott
    2. //I give anyone permission to use it
    3. //Please share any useful edits you make to the script
    4.  
    5. var textField = new Array ("Type your message message here.", "", "", "", "", "");
    6. var chatboxWidth = 300;
    7. var chatboxHeight = 20;
    8.  
    9. function OnGUI () {
    10.  
    11.     textField[0] = GUI.TextArea (Rect (0, Screen.height - chatboxHeight, chatboxWidth, chatboxHeight), textField[0]);
    12.    
    13.     GUI.Label (Rect (0, Screen.height - chatboxHeight * 2, chatboxWidth, chatboxHeight), textField[1]);
    14.     GUI.Label (Rect (0, Screen.height - chatboxHeight * 3, chatboxWidth, chatboxHeight), textField[2]);
    15.     GUI.Label (Rect (0, Screen.height - chatboxHeight * 4, chatboxWidth, chatboxHeight), textField[3]);
    16.     GUI.Label (Rect (0, Screen.height - chatboxHeight * 5, chatboxWidth, chatboxHeight), textField[4]);
    17.     GUI.Label (Rect (0, Screen.height - chatboxHeight * 6, chatboxWidth, chatboxHeight), textField[5]);
    18.  
    19. }
    20.  
    21. function Update () {
    22.     if (Input.GetKeyDown ("return")){
    23.         textField.Unshift("");
    24.     }
    25. }
     
  2. AkilaeTribe

    AkilaeTribe

    Joined:
    Jul 4, 2010
    Posts:
    1,149
    - Make an array which contains all quotes.
    - When someone press Enter, it broadcast his message.
    - Every player add the message to its own array.

    - Use GUILayout.Label rather than GUI.
     
  3. cerebrate

    cerebrate

    Joined:
    Jan 8, 2010
    Posts:
    261
    basically copy-pasta from the m2h networking tutorial, with some minor changes. You'll need to change the window Rect lines in order for it to work correctly. Attach to a gameObject with a networkView.

    Code (csharp):
    1. /*
    2. *  This file is part of the Unity networking tutorial by M2H ([url]http://www.M2H.nl[/url])
    3. *  The original author of this code is Mike Hergaarden, even though some small parts
    4. *  are copied from the Unity tutorials/manuals.
    5. *  Feel free to use this code for your own projects, drop us a line if you made something exciting!
    6. */
    7. #pragma strict
    8.  
    9.  
    10. public static var usingChat : boolean = false;  //Can be used to determine if we need to stop player movement since we're chatting
    11. var skin : GUISkin;                     //Skin
    12. static var showChat : boolean= false;           //Show/Hide the chat
    13.  
    14. //Private vars used by the script
    15. private var inputField : String= "";
    16.  
    17. private var scrollPosition : Vector2;
    18. private var width : int= 190;
    19. private var height : int= 180;
    20. private var playerName : String;
    21. private var lastUnfocus : float =0;
    22. private var window : Rect;
    23. private var lastEntry : float = 0.0;
    24. private var netView : NetworkView;
    25. private static var thisScript : FPSChat;
    26.    
    27. private var chatEntries = new ArrayList();
    28. class FPSChatEntry
    29. {
    30.     var name : String= "";
    31.     var text : String= ""; 
    32. }
    33.  
    34.  
    35. function Awake(){
    36.     usingChat=false;
    37.    
    38.     netView = networkView;
    39.     thisScript = this;
    40.    
    41.     window = Rect(Screen.width-185, 20 + scoreBoard.scoreBoardHeight, width, height);
    42.     lastEntry = Time.time;
    43.    
    44.     playerName = PlayerPrefs.GetString("playerName", "");
    45.     if(!playerName || playerName==""){
    46.         playerName = "RandomName"+Random.Range(1,999);
    47.     }  
    48. }
    49.  
    50. function CloseChatWindow ()
    51. {
    52.     showChat = false;
    53.     inputField = "";
    54.     chatEntries = new ArrayList();
    55. }
    56.  
    57. function ShowChatWindow ()
    58. {
    59.     showChat = true;
    60.     inputField = "";
    61.     chatEntries = new ArrayList();
    62. }
    63.  
    64. function OnGUI ()
    65. {
    66.     if(!showChat){
    67.         return;
    68.     }
    69.    
    70.     if (PlayerInfos.ScreenState()  PlayerInfos.IsUsingStore()){
    71.         return;
    72.     }
    73.    
    74.     GUI.skin = skin;
    75.    
    76.     window.y = 20 + scoreBoard.scoreBoardHeight;
    77.            
    78.     if (Event.current.type == EventType.keyDown  Event.current.character == "\n"  inputField.Length <= 0)
    79.     {
    80.         if(lastUnfocus+0.25<Time.time){
    81.             usingChat=true;
    82.             GUI.FocusWindow(5);
    83.             GUI.FocusControl("Chat input field");
    84.             Screen.lockCursor = false;
    85.         }
    86.     }
    87.     if (Time.time - lastEntry > 10  Network.isServer){
    88.         addGameChatMessage(" ");
    89.         lastEntry = Time.time;
    90.     }
    91.  
    92.     //Screen.lockCursor = screenLock;
    93.     window = GUI.Window (5, window, GlobalChatWindow, "");
    94. }
    95.  
    96.  
    97. function GlobalChatWindow (id : int) {
    98.    
    99.     GUILayout.BeginVertical();
    100.     GUILayout.Space(10);
    101.     GUILayout.EndVertical();
    102.    
    103.     // Begin a scroll view. All rects are calculated automatically -
    104.     // it will use up any available screen space and make sure contents flow correctly.
    105.     // This is kept small with the last two parameters to force scrollbars to appear.
    106.     scrollPosition = GUILayout.BeginScrollView (scrollPosition);
    107.  
    108.     for (var entry : FPSChatEntry in chatEntries)
    109.     {
    110.         GUILayout.BeginHorizontal();
    111.         if(entry.name==""){//Game message
    112.             GUILayout.Label (entry.text);
    113.         }else{
    114.             GUILayout.Label (entry.name+": "+entry.text);
    115.         }
    116.         GUILayout.EndHorizontal();
    117.         GUILayout.Space(3);
    118.        
    119.     }
    120.     // End the scrollview we began above.
    121.     GUILayout.EndScrollView ();
    122.    
    123.     if (Event.current.type == EventType.keyDown  Event.current.character == "\n"  inputField.Length > 0)
    124.     {
    125.         HitEnter(inputField);
    126.     }
    127.     else if (Event.current.type == EventType.keyDown  Event.current.character == "\n"  inputField.Length == 0){
    128.         inputField = ""; //Clear line
    129.         GUI.UnfocusWindow ();//Deselect chat
    130.         lastUnfocus=Time.time;
    131.         usingChat=false;
    132.         Screen.lockCursor = true;
    133.     }
    134.     GUI.SetNextControlName("Chat input field");
    135.     inputField = GUILayout.TextField(inputField);
    136.    
    137.    
    138.     if(Input.GetKeyDown("mouse 0")){
    139.         if(usingChat){
    140.             usingChat=false;
    141.             GUI.UnfocusWindow ();//Deselect chat
    142.             lastUnfocus=Time.time;
    143.         }
    144.     }
    145.     //if (Screen.lockCursor == false){
    146.         //if(usingChat){
    147.             //usingChat=false;
    148.             //GUI.UnfocusWindow ();//Deselect chat
    149.             //lastUnfocus=Time.time;
    150.         //}
    151.     //}
    152. }
    153.  
    154. function HitEnter(msg : String){
    155.     msg = msg.Replace("\n", "");
    156.     netView.RPC("ApplyGlobalChatText", RPCMode.All, playerName, msg);
    157.     inputField = ""; //Clear line
    158.     GUI.UnfocusWindow ();//Deselect chat
    159.     lastUnfocus=Time.time;
    160.     usingChat=false;
    161.     Screen.lockCursor = true;
    162. }
    163.  
    164. static function StaticMsg(msg : String){
    165.     thisScript.HitEnter(msg);
    166. }
    167.  
    168.  
    169. @RPC
    170. function ApplyGlobalChatText (name : String, msg : String)
    171. {
    172.     var entry : FPSChatEntry = new FPSChatEntry();
    173.     entry.name = name;
    174.     entry.text = msg;
    175.  
    176.     chatEntries.Add(entry);
    177.     lastEntry = Time.time;
    178.    
    179.     //Remove old entries
    180.     if (chatEntries.Count > 4){
    181.         chatEntries.RemoveAt(0);
    182.     }
    183.  
    184.     scrollPosition.y = 1000000;
    185. }
    186.  
    187. //Add game messages etc
    188. function addGameChatMessage(str : String){
    189.     ApplyGlobalChatText("", str);
    190.     if(Network.connections.length>0){
    191.         networkView.RPC("ApplyGlobalChatText", RPCMode.Others, "", str);   
    192.     }  
    193. }
     
    tigerleapgorge likes this.
  4. MythStrott

    MythStrott

    Joined:
    Jul 2, 2010
    Posts:
    64
    This was a lot simpler than I thought it would be.

    I have it fully functioning for somebody to chat with himself in a single-player game. Feel free to contribute your knowledge to make it more useful.

    I'll put the script on my first post.

    Thanks!
     
    tigerleapgorge likes this.
  5. MrRudak

    MrRudak

    Joined:
    Oct 17, 2010
    Posts:
    159
    cool thanks
     
    tigerleapgorge likes this.
  6. spav1789

    spav1789

    Joined:
    Sep 13, 2010
    Posts:
    11
    I'm trying to expand this so text displays multiple lines as I'm trying to create one for an mmo in which chat is important. My problem is that I don't know when GUI.Label will wrap the text to the next line as different characters take up different amount of text. Is there any way to know when this will happen or am I just going to have to slice strings at a certain characters and disregard that some words are cut off?
     
  7. Pommimonni

    Pommimonni

    Joined:
    Sep 18, 2013
    Posts:
    2
    I modified and simplified cerebrate's script to make this. It is drawn relative to GUILayout, the input field is hidden when unfocused (i think it's good for an in-game chat), timetag is added and I translated it to C#. I also removed some functionality that I didn't need in the original script.

    Maybe this helps someone. Attach it to a gameobject with with a networkview and call it's draw() function from the OnGUI() function in your GUI script in the part of your GUILayout where you want it. Picture of the chat attached. Modify the looks by changing your GUI.skin

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5.  
    6. public class ChatMaster : MonoBehaviour {
    7.  
    8.     class ChatEntry{
    9.         public string name = "";
    10.         public string message = "";
    11.         public string timeTag = "";
    12.     }
    13.    
    14.     ArrayList entries;
    15.     Vector2 currentScrollPos = new Vector2();
    16.     string inputField = "";
    17.     bool chatInFocus = false;
    18.     string inputFieldFocus = "CIFT";
    19.     bool absPos = false;
    20.    
    21.     void Awake () {
    22.         InitializeChat();
    23.     }
    24.    
    25.     void InitializeChat(){
    26.         entries = new ArrayList();
    27.         unfocusChat();
    28.     }
    29.  
    30.     //draw the chat box in size relative to your GUIlayout
    31.     public void Draw(){
    32.         ChatWindow();
    33.     }
    34.  
    35.     void ChatWindow(){
    36.         GUILayout.BeginVertical();
    37.         currentScrollPos = GUILayout.BeginScrollView(currentScrollPos, GUILayout.MaxWidth(1000), GUILayout.MinWidth(1000)); //limits the chat window size to max 1000x1000, remove the restraints if you want
    38.  
    39.         foreach(ChatEntry ent in entries){
    40.             GUILayout.BeginHorizontal();
    41.             GUI.skin.label.wordWrap = true;
    42.             GUILayout.Label(ent.timeTag + " "+ ent.name + ": "+ent.message);
    43.             GUILayout.EndHorizontal();
    44.             GUILayout.Space(3);
    45.         }
    46.  
    47.         GUILayout.EndScrollView();
    48.         if(chatInFocus){
    49.             GUI.SetNextControlName(inputFieldFocus);
    50.             inputField = GUILayout.TextField(inputField, GUILayout.MaxWidth(1000), GUILayout.MinWidth(1000));
    51.             GUI.FocusControl(inputFieldFocus);
    52.         }
    53.         GUILayout.EndVertical();
    54.  
    55.         if(chatInFocus){
    56.             HandleNewEntries();
    57.         } else {
    58.             checkForInput();
    59.         }
    60.  
    61.     }
    62.  
    63.     void unfocusChat(){
    64.         //Debug.Log("unfocusing chat");
    65.         inputField = "";
    66.         chatInFocus = false;
    67.     }
    68.  
    69.     void checkForInput(){
    70.         if(Event.current.type == EventType.KeyDown  Event.current.character == '\n'  !chatInFocus){
    71.             GUI.FocusControl(inputFieldFocus);
    72.             chatInFocus = true;
    73.             currentScrollPos.y = float.PositiveInfinity;
    74.         }
    75.     }
    76.  
    77.     void HandleNewEntries(){
    78.         if(Event.current.type == EventType.KeyDown  Event.current.character == '\n'){
    79.             if(inputField.Length <= 0){
    80.                 unfocusChat();
    81.                 Debug.Log("unfocusing chat (empty entry)");
    82.                 return;
    83.             }
    84.             networkView.RPC ("AddChatEntry", RPCMode.All, "Cookie monster", inputField);
    85.             //AddChatEntry("Cookie monster", inputField); //for offline testing
    86.             unfocusChat();
    87.             //Debug.Log("unfocusing chat and entry sent");
    88.         }
    89.     }
    90.  
    91.     [RPC]
    92.     void AddChatEntry(string name, string msg){
    93.         ChatEntry newEntry = new ChatEntry();
    94.         newEntry.name = name;
    95.         newEntry.message = msg;
    96.         newEntry.timeTag = "["+System.DateTime.Now.Hour.ToString()+":"+System.DateTime.Now.Minute.ToString()+"]";
    97.         entries.Add(newEntry);
    98.         currentScrollPos.y = float.PositiveInfinity;
    99.     }
    100. }
    101.  
    $csharpchatbox.png
     
    entropicjoey1 likes this.
  8. ShadowCreations

    ShadowCreations

    Joined:
    Aug 13, 2014
    Posts:
    2
    HELP how do i put this into the game for the player can be able to type into chat PLZ HELP
     
  9. Rbert

    Rbert

    Joined:
    Jul 13, 2014
    Posts:
    28
    can you help me about this code..i want to have a button permanent next and preview..a slideshow..
    public class HorizontalTransitionGUI : MonoBehaviour
    {
    //A 4x4 Matrix
    private Matrix4x4 trsMatrix;
    //A three dimension vector that will translate GUI coordinate system
    private Vector3 positionVec;
    //Two booleans to determine which of the GUI buttons have been pressed
    private bool next = false;
    private bool back = false;

    // Use this for initialization
    void Start()
    {
    //Initialize the matrix
    trsMatrix = Matrix4x4.identity;
    //Initialize the Vector
    positionVec = Vector3.zero;
    }

    // Update is called once per frame
    void Update()
    {
    //If the 'next' boolean is true
    if(next)
    {
    //Interpolate the current vector x component until it has the same as value the screen width
    positionVec.x = Mathf.SmoothStep(positionVec.x, Screen.width,Time.deltaTime*10);
    /*Make 'trsMatrix' a matrix that translates, rotates and scales the GUI.
    The position is set to positionVec, the Quaternion is set to identity
    and the scale is set to one.*/
    trsMatrix.SetTRS(positionVec , Quaternion.identity, Vector3.one);
    }
    else if(back) //If 'back is true'
    {
    //Interpolate the current vector x component until it reaches zero
    positionVec.x = Mathf.SmoothStep(positionVec.x, 0,Time.deltaTime*10);
    //Make 'trsMatrix' a matrix that translates, rotates and scales the GUI.
    trsMatrix.SetTRS(positionVec , Quaternion.identity, Vector3.one);
    }

    }

    void OnGUI()
    {
    //The GUI matrix must changed to the trsMatrix
    GUI.matrix = trsMatrix;

    //If the button labeled 'Next' is pressed
    if(GUI.Button(new Rect(Screen.width - 400, 315, 100, 30),"Next"))
    {
    next = true;
    back = false;
    }

    //The TextArea that appears on the first screen.
    GUI.TextArea(new Rect(300,200,Screen.width-600,100), "Click on the 'Next' button to change the Text Area.");

    //If the button labeled 'Back' is pressed
    if(GUI.Button(new Rect(-Screen.width + 300, 315, 100, 30),"Back"))
    {
    next = false;
    back = true;
    }

    //The TextArea that appears on the second screen
    GUI.TextArea(new Rect(-Screen.width + 300,200,Screen.width-600,100), "Click on the 'Back' button to return to the previous Text Area.");

    //To reset to GUI matrix, just make it equal to a 4x4 identity matrix
    GUI.matrix = Matrix4x4.identity;


    }
    }