unity3d的网络使用的简单Demo
网络是游戏非常的重要组成部分,它可以给游戏添加不少乐趣。unity3d本身就封装好Network类,它可以帮助我们快速的在本地建立一个局域网。
首先在unity中创建GameController 类;把它挂载带Main Camera上。
using UnityEngine; using System.Collections; public class GameController : MonoBehaviour { private int connectNum = 10;//客服端的链接数量 private int port = 8899;//端口号 private string ip = "127.0.0.1";//IP地址 public GameObject cube;//游戏的预制对象 void OnGUI() { if(GUILayout.Button("创建服务器")) { Network.InitializeServer(connectNum, port);//创建服务器 } if(GUILayout.Button("链接服务器")) { Network.Connect(ip, port);//链接服务器 } }
//初始化服务器 public void OnServerInitialized() { NetworkPlayer player = Network.player; int group = int.Parse(player + "");//每个客户端的唯一标识 GameObject go = Network.Instantiate(cube, cube.transform.position, cube.transform.rotation,group) as GameObject;//生成游戏对象 go.networkView.RPC("PlayerState", RPCMode.AllBuffered, player);//远程调用PlayerState方法,player是方法的需要传递的参数
}
//链接服务器时unity3d自动调用的方法
public void OnConnectedToServer()
{
NetworkPlayer player = Network.player;
int group = int.Parse(player + "");
GameObject go = Network.Instantiate(cube, cube.transform.position, cube.transform.rotation, group) as GameObject;
go.networkView.RPC("PlayerState",RPCMode.AllBuffered,player);
}
}
然后在unity中创建Plane和Cube,Plane用来作为地面。在创建PlayerMove脚本挂载到Cube上,在Cube的Inspector面板点击Add Component,添加Character Controller和NetWork View两个组件。
using UnityEngine; using System.Collections; public class PlayerMove : MonoBehaviour { private CharacterController controller; public float speed = 8; // Use this for initialization void Start () { controller = this.GetComponent<CharacterController>(); } // Update is called once per frame void Update () { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); Vector3 v1 = new Vector3(h, 0, v); controller.SimpleMove(v1 * speed); } }
在创建Player脚本,挂载到Cube上。
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { private CharacterController controller; // Use this for initialization void Start () { controller = this.GetComponent<CharacterController>(); } //禁用掉CharacterController组件,Cunbe就无法移动 public void LooseControll() { controller = this.GetComponent<CharacterController>(); controller.enabled = false; } [RPC] public void PlayerState(NetworkPlayer player) {
//判断游戏对象是不是本客户端所创建的游戏对象,如果不是就失去对游戏对象的控制。 if(Network.player!=player) { LooseControll(); } } }
最后把Cube制作成预制物体。
由于unity不能同时运行两个程序,所以要把制作成的Demo打包成exe程序,在同时打开两个exe程序。一个作为服务器端,另一个作为客服端。