using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEngine.Networking;
//[AddComponentMenu("MyComponent/My")]//给菜单栏上的component菜单添加一个子菜单(修饰一个类)
publicclassAttributeScript:MonoBehaviour{
//[Commend]修饰方法,(写在方法前)客户端调用,服务器执行
//[ClientRpc]服务器调用,客户端执行
//[SyncVar]同步变量,写在变量或属性之前
//[SynecVar]
//publicfloathp;同步血量到所有客户端
//[Server]只能在服务器端上运行
//[Client]只能在客户端运行
//卵生Spawn(方法)可以卵生到所有客户端
//[HideInInspector]//只对接下来第一个属性起作用
//publicintnumber;
//publicMyClassmyclass;
//publicstringstr;
voidStart(){
}
voidUpdate(){
}
[ContextMenu("printName")]//给组件的齿轮上添加一个功能
voidPrintName(){
Debug.Log("UnityName");
}
}
publicclassMyEditor{
[MenuItem("MyMenu/MyName")]//添加一个菜单(与component同级的菜单)
staticvoidPrintName(){
Debug.Log("Unity");
}
}
[System.Serializable]//可序列化(让类成员的属性显示出来)
publicclassMyClass{
publicinta;
publicintb;
}
客户端请求连接服务器
usingUnityEngine;
usingSystem.Collections;
usingUnityEngine.UI;
usingUnityEngine.Networking;
usingSystem.Collections.Generic;
publicclassGameController:MonoBehaviour{
//初始化服务器的Button
public Button m_initButton;
//连接服务器的Button
public Button m_connectButton;
//客户端对象
NetworkClient m_client;
voidAwake(){
//实例化客户端对象
m_client=new NetworkClient( );
Application.runInBackground=true;//允许后台运行
}
voidStart( ){
m_initButton.onClick.RemoveAllListeners( );
m_connectButton.onClick.RemoveAllListeners( );
m_initButton.onClick.AddListener(InitServerAction);
m_connectButton.onClick.AddListener(ConnectServerAction);
}
voidUpdate( ){
}
#regionbutton点击事件
void InitServerAction ( ){
//启动服务器(监听接口)
NetworkServer.Listen(10000);
//注册事件
NetworkServer.RegisterHandler(MsgType.Connect,OnSeverAddPlayer);
//m_client=ClientScene.ConnectLocalServer( );
//m_client.RegisterHandler(MsgType.Connect,OnConnectServer);
}
void ConnectServerAction( ){
string ip="192.168.10.18";//本机IP地址
try{
m_client.Connect(ip,10000);
m_client.RegisterHandler(MsgType.Connect,OnConnectServer);
}catch(System.Exceptionex){
Debug.Log("连接服务器错误,IP="+ip+ex.Message);
}
}
#endregion
//服务器端检测到客户端的连接的回调方法
void OnSeverAddPlayer(NetworkMessage msg){
print("AddPlayer");
}
//客户端连接成功之后的回调方法
void OnConnectServer(NetworkMessage msg){
print("OnConnectServer");
}
}
网友评论