玩家与物品接触后的判定
if (hit != null && hit.CompareTag("Item"))
{
Debug.Log("捡东西");
var worldItem = hit.gameObject.GetComponent<WorldItem>();
if (worldItem != null)
{
var inventory = GetComponent<PlayerInventory>();
if (inventory != null)
{
inventory.TryPickItem(worldItem);
}
}
}
玩家的背包脚本
分3部分:
公共函数TryPickItem(实际上也是客户端的玩家调用)
发给服务端的函数:申请捡东西
服务端发给客户端的函数:广播客户端修改物品
using UnityEngine;
using Mirror;
using System.Collections.Generic;
public class PlayerInventory : NetworkBehaviour
{
public List<Item> items = new List<Item>();
// 提供给外部调用的公共函数
public void TryPickItem(WorldItem targetItem)
{
if (!isLocalPlayer || targetItem == null) return;
Debug.Log("TryPick");
CmdPickItem(targetItem.netId);
}
// 服务器端命令函数,用于处理捡取物品的逻辑
[Command]
void CmdPickItem(uint netId)
{
Debug.Log("发送捡东西");
if (NetworkServer.spawned.TryGetValue(netId, out var itemIdentity))
{
var worldItem = itemIdentity.GetComponent<WorldItem>();
if (worldItem != null)
{
Item itemData = worldItem.GetItemData();
items.Add(itemData);
Debug.Log($"服务端:拾取了 {itemData.itemName}");
TargetAddItem(connectionToClient, itemData);
NetworkServer.Destroy(worldItem.gameObject);
}
}
}
// 客户端RPC函数,用于同步物品到客户端
[TargetRpc]
void TargetAddItem(NetworkConnection target, Item item)
{
items.Add(item);
Debug.Log($"客户端:已同步物品 {item.itemName} 到背包");
}
}
结果展示
拾取前
拾取后