Important: UNet is a deprecated solution, and a new Multiplayer and Networking Solution (Netcode for GameObjects) is under development. For more information and next steps see the information on the Unity Netcode for GameObjects website. |
制作多人游戏时,除了同步联网游戏对象的属性之外,可能还需要发送、接收和响应其他信息,如比赛开始时间、玩家加入或离开比赛的时间或特定于游戏类型的其他信息(例如向所有玩家通知在“夺旗”风格游戏中夺得旗帜)。
在 Unity 网络高级 API 中,主要可通过三种方式传输此类信息。
远程操作允许通过网络调用脚本中的方法。可让服务器在所有客户端或特定单个客户端上调用方法。还可让客户端在服务器上调用方法。通过使用远程操作,可以将数据作为参数传递给方法,其具体方式与在本地(非多人玩家)项目中调用方法的方式非常类似。
网络回调允许挂接到在游戏过程中发生的内置 Unity 事件,例如玩家加入或离开时,创建或销毁游戏对象时,或加载新场景时。可以实现两种类型的网络回调:
Network Manager 回调,适用于与 Network Manager 自身有关的回调(比如,客户端连接或断开连接时)
Network Behaviour 回调,适用于与单个联网游戏对象相关的回调(例如,当调用其 Start 函数时,或者有新玩家加入游戏时此特定游戏对象应该执行什么操作)
网络消息是一种发送消息的“低级”方法(但仍被归类为网络“高级 API”的一部分)。它们允许使用脚本直接在客户端和服务器之间发送数据。可以发送基本类型的数据(int、string 等)以及最常见的 Unity 类型(例如 Vector3)。由于您对此采用自定义实现,因此这些消息不直接与任何特定的游戏对象或 Unity 事件相关联:您可以自行决定其目的并实现它们!
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.