解决方案
- 将所有层级中的对象添加
NetworkIdentity
- 忽略警告
Prefab 'xxx' has several NetworkIdentity components attached to itself or its children, this is not supported.
- 通过脚本手动处理网络层级
我们需要确保客户端只在有父对象时才接收到子对象。同时,我们需要确保客户端在收到父对象后能够尽快地接收到子对象。
这可以通过OnRebuildObservers
和OnCheckObserver
实现。这些方法检查客户端是否有父对象,如果有,则将玩家连接添加到观察者列表中,从而导致玩家接收该对象。
当生成父对象时,还需要调用NetworkIdentity.RebuildObservers
。这是由自定义连接类实现的,该类在客户端上生成对象时通知MultiplayerGame
(连接发送Spawn消息)。
完整脚本如下。
NetworkChild
用于子对象网络组件的基类,例如马车、马车内的对象。
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public abstract class NetworkChild : NetworkBehaviour
{
private NetworkIdentity m_networkParent;
[SyncVar(hook = "OnNetParentChanged")]
private NetworkInstanceId m_networkParentId;
public NetworkIdentity NetworkParent
{
get { return m_networkParent; }
}
#region Server methods
public override void OnStartServer()
{
UpdateParent();
base.OnStartServer();
}
[ServerCallback]
public void RefreshParent()
{
UpdateParent();
GetComponent<NetworkIdentity>().RebuildObservers(false);
}
void UpdateParent()
{
NetworkIdentity parent = transform.parent != null ? transform.parent.GetComponentInParent<NetworkIdentity>() : null;
m_networkParent = parent;
m_networkParentId = parent != null ? parent.netId : NetworkInstanceId.Invalid;
}
public override bool OnCheckObserver(NetworkConnection conn)
{
m_networkParentId = m_networkParent != null ? m_networkParent.netId : NetworkInstanceId.Invalid;
if (m_networkParent != null && m_networkParent.observers != null)
{
return m_networkParent.observers.Contains(conn);
}
return false;
}
public override bool OnRebuildObservers(HashSet<NetworkConnection> observers, bool initialize)
{
m_networkParentId = m_networkParent != null ? m_networkParent.netId : NetworkInstanceId.Invalid;
if (m_networkParent != null && m_networkParent.observers != null)
{
foreach (var parentObserver in m_networkParent.observers)
{
observers.Add(parentObserver);
}
}
return true;
}
#endregion
#region Client Methods
public override void OnStartClient()
{
base.OnStartClient();
FindParent();
}
void OnNetParentChanged(NetworkInstanceId newNetParentId)
{
if (m_networkParentId != newNetParentId)
{
m_networkParentId = newNetParentId;
FindParent();
OnParentChanged();
}
}
protected virtual void OnParentChanged()
{
}
private void FindParent()
{
if (NetworkServer.localClientActive)
{
return;
}
if (!ClientScene.objects.TryGetValue(m_networkParentId, out m_networkParent))
{
Debug.AssertFormat(false, "NetworkChild, parent object {0} not found", m_networkParentId);
}
}
#endregion
}
NetworkNotifyConnection
这是一个自定义连接类,当发送Spawn和Destroy消息到客户端时会通知MultiplayerGame
。
注:本文中的“Spawn”和“Destroy”是指游戏中创建或销毁角色或物品的操作。
using System;
using UnityEngine;
using UnityEngine.Networking;
public class NetworkNotifyConnection : NetworkConnection
{
public MultiplayerGame Game;
public override void Initialize(string networkAddress, int networkHostId, int networkConnectionId, HostTopology hostTopology)
{
base.Initialize(networkAddress, networkHostId, networkConnectionId, hostTopology);
Game = NetworkManager.singleton.GetComponent<MultiplayerGame>();
}
public override bool SendByChannel(short msgType, MessageBase msg, int channelId)
{
Prefilter(msgType, msg, channelId);
if (base.SendByChannel(msgType, msg, channelId))
{
Postfilter(msgType, msg, channelId);
return true;
}
return false;
}
private void Prefilter(short msgType, MessageBase msg, int channelId)
{
}
private void Postfilter(short msgType, MessageBase msg, int channelId)
{
if (msgType == MsgType.ObjectSpawn || msgType == MsgType.ObjectSpawnScene)
{
Game.OnObjectSpawn(NetworkExtensions.GetObjectSpawnNetId(msg), this);
}
else if (msgType == MsgType.ObjectDestroy)
{
Game.OnObjectDestroy(NetworkExtensions.GetObjectDestroyNetId(msg), this);
}
}
}
多人游戏
NetworkManager
中的组件,在服务器启动时设置自定义网络连接类。
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class MultiplayerGame : MonoBehaviour
{
HashSet<NetworkIdentity> m_dirtyObj = new HashSet<NetworkIdentity>();
private void Start()
{
var net = NetworkManager.singleton;
var host = net.StartHost();
if (host != null)
{
NetworkServer.SetNetworkConnectionClass<NetworkNotifyConnection>();
}
}
public void OnObjectSpawn(NetworkInstanceId objectId, NetworkConnection conn)
{
var obj = NetworkServer.FindLocalObject(objectId);
RefreshChildren(obj.transform);
}
public void OnObjectDestroy(NetworkInstanceId objectId, NetworkConnection conn)
{
}
void RefreshChildren(Transform obj)
{
foreach (var child in obj.GetChildren())
{
NetworkIdentity netId;
if (child.TryGetComponent(out netId))
{
m_dirtyObj.Add(netId);
}
else
{
RefreshChildren(child);
}
}
}
private void Update()
{
NetworkIdentity netId;
while (m_dirtyObj.RemoveFirst(out netId))
{
if (netId != null)
{
netId.RebuildObservers(false);
}
}
}
}