注意:已弃用 UNet,未来会将其从 Unity 中删除。一个新系统正在开发中。如需了解更多信息和后续步骤,请参阅此博客文章以及常见问题解答 (FAQ)。 |
内置的 Network Proximity Checker 组件是用于确定游戏对象网络可见性的内置默认组件。但是,此组件仅提供基于距离的检查。有时可能希望使用其他类型的可见性检查,例如基于网格的规则、视线测试、导航路径测试或适合具体游戏的任何其他类型的测试。
为此,可实现与 Network Proximity Checker 等效的自定义功能。为实现此目的,需要了解 Network Proximity Checker 的工作原理。请参阅 Editor 内的 Network Proximity Checker 组件和 NetworkProximityChecker API 的相关文档。
Network Proximity Checker 是使用 Unity 多玩家 HLAPI 的公共可见性接口实现的。通过同样使用此接口,您可以实现所需的任何类型的可见性规则。每个 NetworkIdentity 都会跟踪可看见该游戏对象的玩家集合。可看见 NetworkIdentity 游戏对象的玩家称为 NetworkIdentity 的“观察者”。
Network Proximity Checker 以固定间隔(使用 Inspector 中的“Vis Update Interval”值进行设置)调用 Network Identity 组件上的 RebuildObservers** **方法,以便在每个玩家移动时更新玩家的网络可见游戏对象的集合。
在 NetworkBehaviour
** **类(联网脚本继承自该类)上,有一些用于确定可见性的虚拟函数。如下:
OnCheckObserver - 当新玩家进入游戏时,对每个联网游戏对象在服务器上调用此方法。如果返回 true,则将该玩家添加到对象的观察者中。NetworkProximityChecker
方法在其对此函数的实现中执行简单的距离检查,并使用 Physics.OverlapSphere()
来查找此对象的可见性距离内的玩家。
OnRebuildObservers - 调用 RebuildObservers
时在服务器上调用此方法。此方法期望用可以看到对象的玩家填充观察者集。然后,NetworkServer 根据新旧可见性集之间的差异来处理 ObjectHide
和 ObjectSpawn
消息的发送。
为了检查任何给定的联网游戏对象是否为玩家,可以检查其 NetworkIdentity
是否存在有效的 connectionToClient。例如:
var hits = Physics.OverlapSphere(transform.position, visRange);
foreach (var hit in hits)
{
//(如果游戏对象具有 connectionToClient,则表示它是玩家)
var uv = hit.GetComponent<NetworkIdentity>();
if (uv != null && uv.connectionToClient != null)
{
observers.Add(uv.connectionToClient);
}
}
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.