unity3d网络编程关键

来源:互联网 发布:java获取本地ip 编辑:程序博客网 时间:2024/05/09 02:14

最近几天研究unity3d的网络编程,小有斩获,列举一些我认为比较重要的关键点。

还在学习阶段,有误的地方还望留言指正,不胜感谢。

1.Network.Instantiate函数

这个函数一般在客户端连接到服务器(服务器也作为游戏的一个player时创建服务器时也应该调用)时在服务器调用。

先看看官网的说明The given prefab will be instanted on all clients in the game. Synchronization is automatically set up so there is no extra work involved. The position, rotation and network group number are given as parameters. Internally this is an RPC call so when Network.RemoveRPCs is called for the group number, the object will be removed. Note that there must be something set to the playerPrefab in the Editor. You can read more about instantiations in the object reference Object.Instantiate.

什么意思呢?就是给定的预设注意在编辑器中必须设置playerPrefab将在所有的客户端上实例化。同步被自动设置,因此没有额外的工作要做。位置、旋转和网络组数值作为给定的参数。这是一个RPC调用,因此,当为该组数Network.RemoveRPCs被调用,这个物体将被移除。

用了这个函数后所有你想创建的物体都会在所有的客户端调用并实例化,如果只是做对战类游戏,不用socket编程的话,简直方便。

2.Network.OnSerializeNetworkView函数

这个函数可以传输一些自定义的数据,比如人物的血量,怪物掉血等数据,在客户端连接到服务器时自动调用。它的发送取决于谁拥有该物体,即所有者发送,其他所有人接收。

举个例子:

using UnityEngine;using System.Collections;// This objects health information//这个物体的生命信息public class example : MonoBehaviour {public int currentHealth;void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info) {int health = 0;if (stream.isWriting) {health = currentHealth;stream.Serialize(ref health);} else {stream.Serialize(ref health);currentHealth = health;}}}

3.其他

//Client functions called by Unityfunction OnConnectedToServer() {Debug.Log("This CLIENT has connected to a server");}function OnDisconnectedFromServer(info : NetworkDisconnection) {Debug.Log("This SERVER OR CLIENT has disconnected from a server");}function OnFailedToConnect(error: NetworkConnectionError){Debug.Log("Could not connect to server: "+ error);}//Server functions called by Unityfunction OnPlayerConnected(player: NetworkPlayer) {Debug.Log("Player connected from: " + player.ipAddress +":" + player.port);}function OnServerInitialized() {Debug.Log("Server initialized and ready");}function OnPlayerDisconnected(player: NetworkPlayer) {Debug.Log("Player disconnected from: " + player.ipAddress+":" + player.port);}//othersfunction OnFailedToConnectToMasterServer(info: NetworkConnectionError){Debug.Log("Could not connect to master server: "+ info);}function OnNetworkInstantiate (info : NetworkMessageInfo) {Debug.Log("New object instantiated by " + info.sender);}function OnSerializeNetworkView(stream : BitStream, info : NetworkMessageInfo){//Custom code here (your code!)}

0 0
原创粉丝点击