Chat in game

I didn’t know if I should post it here or in the networking section but here it is!

So I’m trying to add a gui chat system for my game and I dont really know how to do it! I would guess it’s done with some sort of array but I haven’t used arrays that much so I dont know how to implement it! (It is a multiplayer game)
If someone could tell me how to think and get me on the right track that would be great! I dont want to ask for a finished script, only help on how to think so I can make it self!

Tnx!

//Elis

Well you could do what your saying.

Send a chat message as an RPC to all others, and when people receives it save it in a local array, and update chat GUI with the latest x-amount of msgs in the array.

This is a simple approach but it works.

Ok, so I’m on the right track! Now, how could I go ahead and do it? As I said, I’m very new to this! :stuck_out_tongue:

Create a new gameobject for your gui if you havnt already. Also apply a networkview.
Then disable state synchronisation.

Now look at:

Create a TextField and TextArea.
On Input you send the text from the textfield via rpc and add it to your array which is displayed in the textarea.

Here is some procedure, you just have to put the pieces together :slight_smile:

First make an array, I used an ArrayList for this

public ArrayList messages = new ArrayList();

Then make an empty string to temporary store a message in

public string stringToEdit = "";

Make a textfield to enter the message

stringToEdit = GUI.TextField (new Rect (10, 10, 500, 20), stringToEdit, 128);

For a scroll view first create a Vector2

Vector2 scrollView;

Display the actual scroll view and display the chatmessages inside of it

scrollView = GUI.BeginScrollView(new Rect(10, 30, 600, 300), scrollView, new Rect(0, 0, 220, messages.Count * 25));

for(int i = 0; i < messages.Count; i++)
{	
	GUI.Label(new Rect(10,10 + (i * 20),500,20), messages[i].ToString());
}		

GUI.EndScrollView();

Create RPC to send the message across the network

[RPC]
void SendChatMessage(string str1)
{
	messages.Add(str1);
}

Fire the RPC when you hit enter and make the textfield empty for a new message

if (Event.current.type == EventType.keyDown  Event.current.character == '\n')
{
	
	messages.Add(stringToEdit);
	networkView.RPC("SendChatMessage", RPCMode.Others, stringToEdit);
	stringToEdit = "";
}

Remove the oldest message from the array when a certain amount is reached

if (messages.Count == 50)
{
	messages.RemoveAt(0);
}

Don’t forget to attach a NetworkView component to the game object you attach this script to.

Now you only need to set up a server, on this site you will find instructions http://cgcookie.com/unity/2011/12/20/introduction-to-networking-in-unity/

Good luck!

Thank you every body for these tips! :smile:
Now let’s see what I can do with them! :smile: