前言
我们为了设计出更高端上档次的虚拟现实软件或游戏。技术方面离不开链接互联网通讯的部分。在学习或使用网络之前,我们必须先了解和掌握unity3d自带的网络机制的运行原理和方法的使用。为我们以后备战更高难的项目奠定一定的技术基础。为此,对文档对unity3d network 方面的知识进行了一定的分析和总结。如果有对此方面还有新的内容或知识点。我们会在以后逐步添加完善此文档。
在群共享中提供了一个network的工程包,可供大家参考下载。
好现在我们言归正传。现在开始我们的研究。
1.Ip 和 port
提到网络我们不得不说到ip和prot,ip地址我们联网时设计的是本机也就是“127.0.0.1”也可以用自己的ip比如说“192.168.1.15”等,端口号是0-65535之间的整数。是登陆这个ip的门。ip就像是房间一样。有了房间和门牌号我们就能知道我们要登录哪个地方了。
2.server
当我们有了ip和port以后,首先我们要知道的是我们需要建立一个服务。因为unity3d的联机机制是先建立服务,然后大家通过链接的服务才能进入并连接。
network提供一个方法叫做InitializeServer初始化服务器。
static function InitializeServer (connections : int, listenPort : int, useNat : bool) : NetworkConnectionError
connections是允许的入站连接或玩家的数量,listenPort是要监听的端口,useNat设置NAT穿透功能。如果你想要这个服务器能够接受连接使用NAT穿透,使用facilitator,设置这个为true。
我们的写法是这样的Network.InitializeServer(32,25000, false);要这个最大连接数为32个客户端,监听端口我们设置和登录的port一致都为25000,我们不用nat穿透所以第三项我们设置为false;
3.connect 这个方法就是其他客户端连接这个服务的方法了。 static function Connect (IP : string, remotePort : int, password : string = "") : NetworkConnectionError Network.Connect("127.0.0.1", 25000);
OnPlayerConnected
Called on the server whenever a new player has successfullyconnected.
每当一个新玩家成功连接时,在服务器上调用这个函数。
Called on the server whenever a Network.InitializeServer wasinvoked and has completed.
每当一个Network.InitializeServer被调用并完成时,在服务器上调用这个函数。
Called on the client when you have successfully connected to aserver
当成功连接到服务器时,在客户端调用这个函数。
Called on the server whenever a player is disconnected from theserver
每当一个玩家从服务器断开时,在服务器调用这个函数。
Called on client during disconnection from server, but also onthe server when the connection has disconnected.
在服务器上当连接已经断开,在客户端调用这个函数。
Called on the client when a connection attempt fails for somereason.
当一个连接因为某些原因失败时,从客户端调用这个函数。
Called on clients or servers when there is a problem connectingto the master server.
当连接到主服务器(MasterServer)有问题时,从客户端或服务器调用这个函数。
Called on objects which have been network instantiated withNetwork.Instantiate
当一个物体使用Network.Instantiate已经网络实例化,在该物体上调用这个函数。
Used to customize synchronization of variables in a scriptwatched by a network view.
用来在一个由网络视图监控的脚本中自定义变量同步。
在其中添加对应的方法就可以定义操作了.
本文详细介绍了Unity3D网络机制的基础概念,包括IP地址、端口号、服务器与客户端的交互过程。通过具体代码示例展示了如何初始化服务器、连接服务,以及网络事件回调函数的使用。
2312

被折叠的 条评论
为什么被折叠?



