unity3d网络编程关键

最近几天研究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 Unity
function 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 Unity
function 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);
}

//others
function 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值