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

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

//This script was originally made by MythStrott
//I give anyone permission to use it
//Please share any useful edits you make to the script

var textField = new Array ("Type your message message here.", "", "", "", "", "");
var chatboxWidth = 300; 
var chatboxHeight = 20;

function OnGUI () {

	textField[0] = GUI.TextArea (Rect (0, Screen.height - chatboxHeight, chatboxWidth, chatboxHeight), textField[0]); 
    
	GUI.Label (Rect (0, Screen.height - chatboxHeight * 2, chatboxWidth, chatboxHeight), textField[1]);
	GUI.Label (Rect (0, Screen.height - chatboxHeight * 3, chatboxWidth, chatboxHeight), textField[2]);
	GUI.Label (Rect (0, Screen.height - chatboxHeight * 4, chatboxWidth, chatboxHeight), textField[3]);
	GUI.Label (Rect (0, Screen.height - chatboxHeight * 5, chatboxWidth, chatboxHeight), textField[4]);
	GUI.Label (Rect (0, Screen.height - chatboxHeight * 6, chatboxWidth, chatboxHeight), textField[5]);

} 

function Update () {
	if (Input.GetKeyDown ("return")){
		textField.Unshift("");
	}
}
  • 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.

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.

/* 
*  This file is part of the Unity networking tutorial by M2H ([url]http://www.M2H.nl[/url])
*  The original author of this code is Mike Hergaarden, even though some small parts 
*  are copied from the Unity tutorials/manuals.
*  Feel free to use this code for your own projects, drop us a line if you made something exciting! 
*/
#pragma strict


public static var usingChat : boolean = false;	//Can be used to determine if we need to stop player movement since we're chatting
var skin : GUISkin;						//Skin
static var showChat : boolean= false;			//Show/Hide the chat

//Private vars used by the script
private var inputField : String= "";

private var scrollPosition : Vector2;
private var width : int= 190;
private var height : int= 180;
private var playerName : String;
private var lastUnfocus : float =0;
private var window : Rect;
private var lastEntry : float = 0.0;
private var netView : NetworkView;
private static var thisScript : FPSChat;
	
private var chatEntries = new ArrayList();
class FPSChatEntry
{
	var name : String= "";
	var text : String= "";	
}


function Awake(){
	usingChat=false;
	
	netView = networkView;
	thisScript = this;
	
	window = Rect(Screen.width-185, 20 + scoreBoard.scoreBoardHeight, width, height);
	lastEntry = Time.time;
	
	playerName = PlayerPrefs.GetString("playerName", "");
	if(!playerName || playerName==""){
		playerName = "RandomName"+Random.Range(1,999);
	}	
}

function CloseChatWindow ()
{
	showChat = false;
	inputField = "";
	chatEntries = new ArrayList();
}

function ShowChatWindow ()
{
	showChat = true;
	inputField = "";
	chatEntries = new ArrayList();
}

function OnGUI ()
{
	if(!showChat){
		return;
	}
	
	if (PlayerInfos.ScreenState()  PlayerInfos.IsUsingStore()){
		return;
	}
	
	GUI.skin = skin;
	
	window.y = 20 + scoreBoard.scoreBoardHeight;
			
	if (Event.current.type == EventType.keyDown  Event.current.character == "\n"  inputField.Length <= 0)
	{
		if(lastUnfocus+0.25<Time.time){
			usingChat=true;
			GUI.FocusWindow(5);
			GUI.FocusControl("Chat input field");
			Screen.lockCursor = false;
		}
	}
	if (Time.time - lastEntry > 10  Network.isServer){
		addGameChatMessage(" ");
		lastEntry = Time.time;
	}

	//Screen.lockCursor = screenLock;
	window = GUI.Window (5, window, GlobalChatWindow, "");
}


function GlobalChatWindow (id : int) {
	
	GUILayout.BeginVertical();
	GUILayout.Space(10);
	GUILayout.EndVertical();
	
	// Begin a scroll view. All rects are calculated automatically - 
    // it will use up any available screen space and make sure contents flow correctly.
    // This is kept small with the last two parameters to force scrollbars to appear.
	scrollPosition = GUILayout.BeginScrollView (scrollPosition);

	for (var entry : FPSChatEntry in chatEntries)
	{
		GUILayout.BeginHorizontal();
		if(entry.name==""){//Game message
			GUILayout.Label (entry.text);
		}else{
			GUILayout.Label (entry.name+": "+entry.text);
		}
		GUILayout.EndHorizontal();
		GUILayout.Space(3);
		
	}
	// End the scrollview we began above.
    GUILayout.EndScrollView ();
	
	if (Event.current.type == EventType.keyDown  Event.current.character == "\n"  inputField.Length > 0)
	{
		HitEnter(inputField);
	}
	else if (Event.current.type == EventType.keyDown  Event.current.character == "\n"  inputField.Length == 0){
		inputField = ""; //Clear line
		GUI.UnfocusWindow ();//Deselect chat
		lastUnfocus=Time.time;
		usingChat=false;
		Screen.lockCursor = true;
	}
	GUI.SetNextControlName("Chat input field");
	inputField = GUILayout.TextField(inputField);
	
	
	if(Input.GetKeyDown("mouse 0")){
		if(usingChat){
			usingChat=false;
			GUI.UnfocusWindow ();//Deselect chat
			lastUnfocus=Time.time;
		}
	}
	//if (Screen.lockCursor == false){
		//if(usingChat){
			//usingChat=false;
			//GUI.UnfocusWindow ();//Deselect chat
			//lastUnfocus=Time.time;
		//}
	//}
}

function HitEnter(msg : String){
	msg = msg.Replace("\n", "");
	netView.RPC("ApplyGlobalChatText", RPCMode.All, playerName, msg);
	inputField = ""; //Clear line
	GUI.UnfocusWindow ();//Deselect chat
	lastUnfocus=Time.time;
	usingChat=false;
	Screen.lockCursor = true;
}

static function StaticMsg(msg : String){
	thisScript.HitEnter(msg);
}


@RPC
function ApplyGlobalChatText (name : String, msg : String)
{
	var entry : FPSChatEntry = new FPSChatEntry();
	entry.name = name;
	entry.text = msg;

	chatEntries.Add(entry);
	lastEntry = Time.time;
	
	//Remove old entries
	if (chatEntries.Count > 4){
		chatEntries.RemoveAt(0);
	}

	scrollPosition.y = 1000000;	
}

//Add game messages etc
function addGameChatMessage(str : String){
	ApplyGlobalChatText("", str);
	if(Network.connections.length>0){
		networkView.RPC("ApplyGlobalChatText", RPCMode.Others, "", str);	
	}	
}
1 Like

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!

1 Like

cool thanks

1 Like

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?

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

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ChatMaster : MonoBehaviour {

	class ChatEntry{
		public string name = "";
		public string message = "";
		public string timeTag = "";
	}
	
	ArrayList entries;
	Vector2 currentScrollPos = new Vector2();
	string inputField = "";
	bool chatInFocus = false;
	string inputFieldFocus = "CIFT";
	bool absPos = false;
	
	void Awake () {
		InitializeChat();
	}
	
	void InitializeChat(){
		entries = new ArrayList();
		unfocusChat();
	}

	//draw the chat box in size relative to your GUIlayout
	public void Draw(){
		ChatWindow();
	}

	void ChatWindow(){
		GUILayout.BeginVertical();
		currentScrollPos = GUILayout.BeginScrollView(currentScrollPos, GUILayout.MaxWidth(1000), GUILayout.MinWidth(1000)); //limits the chat window size to max 1000x1000, remove the restraints if you want

		foreach(ChatEntry ent in entries){
			GUILayout.BeginHorizontal();
			GUI.skin.label.wordWrap = true;
			GUILayout.Label(ent.timeTag + " "+ ent.name + ": "+ent.message);
			GUILayout.EndHorizontal();
			GUILayout.Space(3);
		}

		GUILayout.EndScrollView();
		if(chatInFocus){
			GUI.SetNextControlName(inputFieldFocus);
			inputField = GUILayout.TextField(inputField, GUILayout.MaxWidth(1000), GUILayout.MinWidth(1000));
			GUI.FocusControl(inputFieldFocus);
		}
		GUILayout.EndVertical();

		if(chatInFocus){
			HandleNewEntries();
		} else {
			checkForInput();
		}

	}

	void unfocusChat(){
		//Debug.Log("unfocusing chat");
		inputField = "";
		chatInFocus = false;
	}

	void checkForInput(){
		if(Event.current.type == EventType.KeyDown  Event.current.character == '\n'  !chatInFocus){
			GUI.FocusControl(inputFieldFocus);
			chatInFocus = true;
			currentScrollPos.y = float.PositiveInfinity;
		}
	}

	void HandleNewEntries(){
		if(Event.current.type == EventType.KeyDown  Event.current.character == '\n'){
			if(inputField.Length <= 0){
				unfocusChat();
				Debug.Log("unfocusing chat (empty entry)");
				return;
			}
			networkView.RPC ("AddChatEntry", RPCMode.All, "Cookie monster", inputField);
			//AddChatEntry("Cookie monster", inputField); //for offline testing
			unfocusChat();
			//Debug.Log("unfocusing chat and entry sent");
		}
	}

	[RPC]
	void AddChatEntry(string name, string msg){
		ChatEntry newEntry = new ChatEntry();
		newEntry.name = name;
		newEntry.message = msg;
		newEntry.timeTag = "["+System.DateTime.Now.Hour.ToString()+":"+System.DateTime.Now.Minute.ToString()+"]";
		entries.Add(newEntry);
		currentScrollPos.y = float.PositiveInfinity;
	}
}

1 Like

HELP how do i put this into the game for the player can be able to type into chat PLZ HELP

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.deltaTime10);
/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;

}
}