不管是文字聊天还是语音聊天,都需要先建立聊天室,今天我们就来学习简单的unity 聊天室是怎样建立的。

unity 聊天室

下面看看代码:

 服务端 Server.js:
[javascript] view plaincopyprint?
var connectPort : int = 2278;
function OnGUI ()
{
if (Network.peerType == NetworkPeerType.Disconnected)
{
GUILayout.Label("Connection status: Disconnected");
Network.InitializeServer(32, connectPort, false);
}

}

 客户端 Client.js:
[javascript] view plaincopyprint?
var connectToIP : String = "127.0.0.1";
var connectPort : int = 2288;
var MyName:String="";
var Inputword:String="";
var Outputword:String="";
function OnGUI ()
{
if(Network.peerType == NetworkPeerType.Disconnected){
GUILayout.Label("Connection status: Disconnected");
if(GUILayout.Button("Connect as client"))
{
  //注意:这个Button必须写,如果不写可能会出错。
Network.Connect(connectToIP, connectPort);
}
}
else
{
if(Network.isClient){
MyName=GUI.TextField(Rect(20,20,100,30),MyName,20);
Outputword=GUI.TextArea(Rect(20,50,400,300),Outputword,1000);
Inputword=GUI.TextField(Rect(20,360,300,60),Inputword,200);
if(GUI.Button(Rect(350,360,70,60),"send")){
networkView.RPC("SomeoneSay",RPCMode.All,Inputword,MyName);
Inputword="";
}
}
}
}
@RPC  //注意:networkView.RPC调用的函数必须写 "@RPC"
function SomeoneSay(sayWord:String,name:String){
Outputword =Outputword+"\n"+ name + ":\n" + "  " + sayWord;
}