代码:
using UnityEngine;
using System. Collections;
public class chatroom : MonoBehaviour {
public string remoteIP= "127.0.0.1" ;
public int remotePort= 25000 ;
public int listenPort= 25000 ;
public string remoteGUID= "" ;
public bool useNat= false ;
string MyName= "" ;
string Inputword= "" ;
string Outputword= "" ;
void OnGUI ( ) {
if ( Network. peerType == NetworkPeerType. Disconnected)
{
useNat = GUILayout. Toggle ( useNat, "Use NAT punchthrough" ) ;
GUILayout. BeginVertical ( ) ;
if ( GUILayout. Button ( "Connect" ) )
{
if ( useNat)
{
if ( remoteGUID == null )
Debug. LogWarning ( "Invalid GUID given" ) ;
else
Network. Connect ( remoteGUID) ;
}
else
{
Network. Connect ( remoteIP, remotePort) ;
}
}
if ( GUILayout. Button ( "Start Server" ) )
{
Network. InitializeServer ( 32 , listenPort, useNat) ;
}
GUILayout. EndVertical ( ) ;
if ( useNat)
{
remoteGUID = GUILayout. TextField ( remoteGUID, GUILayout. MinWidth ( 145 ) ) ;
}
else
{
remoteIP = GUILayout. TextField ( remoteIP, GUILayout. MinWidth ( 100 ) ) ;
remotePort = int . Parse ( GUILayout. TextField ( remotePort. ToString ( ) ) ) ;
}
}
else
{
if ( Network. isServer) {
GUI. Label ( new Rect ( 30 , 0 , 500 , 30 ) , "Server GUID: " + Network. player. guid) ;
}
GUI. Label ( new Rect ( 30 , 12 , 500 , 30 ) , "Server Local IP/port: " + Network. player. ipAddress + "/" + Network. player. port) ;
GUI. Label ( new Rect ( 30 , 24 , 500 , 30 ) , "Server External IP/port: " + Network. player. externalIP + "/" + Network. player. externalPort) ;
}
if ( GUI. Button ( new Rect ( 300 , 0 , 100 , 30 ) , "Disconnect" ) ) {
Network. Disconnect ( 200 ) ;
}
GUI. Label ( new Rect ( 30 , 50 , 100 , 30 ) , "Name:" ) ;
MyName= GUI. TextField ( new Rect ( 70 , 48 , 100 , 30 ) , MyName, 10 ) ;
Outputword= GUI. TextArea ( new Rect ( 30 , 80 , 400 , 300 ) , Outputword, 1000 ) ;
Inputword= GUI. TextField ( new Rect ( 30 , 400 , 300 , 60 ) , Inputword, 200 ) ;
if ( GUI. Button ( new Rect ( 350 , 400 , 70 , 60 ) , "send" ) ) {
networkView. RPC ( "SomeoneSay" , RPCMode. All, Inputword, MyName) ;
Inputword= "" ;
}
}
}
void OnServerInitialized ( ) {
if ( useNat)
Debug. Log ( "==> GUID is " + Network. player. guid + ". Use this on clients to connect with NAT punchthrough." ) ;
Debug. Log ( "==> Local IP/port is " + Network. player. ipAddress + "/" + Network. player. port + ". Use this on clients to connect directly." ) ;
}
void OnConnectedToServer ( ) {
print ( "Connected!!" ) ;
}
void OnDisconnectedFromServer ( ) {
if ( this . enabled != false )
Application. LoadLevel ( Application. loadedLevel) ;
}
[ RPC ]
void SomeoneSay ( string message , string name ) {
Outputword = Outputword+ "\n" + name + ": " + message;
}
}
然后创建一个对象:chatroom 将此代码拖到对象上 在inspector窗口为对象添加"Network View"