Unity+PlayFab+Photon:如何让所有玩家看到其他玩家的预制体部件?
解决方案
核心问题分析
- PhotonView引用错误:你当前获取的是预制体的
PhotonView,而非实例化后玩家对象的PhotonView,导致RPC无法正确发送到对应玩家对象。 - 依赖本地静态变量:RPC里使用
PFLogin.body这类本地静态数据,其他客户端的PFLogin存储的是自身玩家的装备,而非远程玩家的,自然找不到正确部件。 - GameObject.Find不可靠:通过硬编码路径查找对象在网络场景中极易出错,应该直接在玩家脚本中引用子组件。
步骤1:重构玩家脚本,添加部件引用
创建PlayerEquipment脚本挂在玩家预制体上,直接在Inspector中拖入对应部件引用,避免动态查找:
using UnityEngine; using Photon.Pun; public class PlayerEquipment : MonoBehaviourPunCallbacks { // 在Inspector面板中拖入所有可选的装备预制体 public GameObject[] bodyOptions; public GameObject[] cloakOptions; public GameObject[] shieldOptions; public GameObject[] weaponOptions; void Start() { // 仅本地玩家初始化并同步装备数据 if (photonView.IsMine) { string body = PFLogin.body; string cloak = PFLogin.cloak; string shield = PFLogin.shield; string weapon = PFLogin.weapon; // 向所有客户端同步当前玩家的装备信息 photonView.RPC("SyncPlayerEquipment", RpcTarget.AllBuffered, body, cloak, shield, weapon); } } [PunRPC] void SyncPlayerEquipment(string targetBody, string targetCloak, string targetShield, string targetWeapon) { // 激活对应装备,禁用其余选项 ToggleSpecificEquipment(bodyOptions, targetBody); ToggleSpecificEquipment(cloakOptions, targetCloak); ToggleSpecificEquipment(shieldOptions, targetShield); ToggleSpecificEquipment(weaponOptions, targetWeapon); } // 通用方法:激活指定名称的装备,禁用同组其他装备 void ToggleSpecificEquipment(GameObject[] equipmentGroup, string targetName) { foreach (var equipment in equipmentGroup) { equipment.SetActive(equipment.name == targetName); } } }
步骤2:修正OnJoinedRoom中的实例化逻辑
确保获取实例化后玩家对象的PhotonView,不再依赖预制体的引用:
public override void OnJoinedRoom() { GameObject spawnedPlayer; if(PFLogin.prefabName == "Female") { spawnedPlayer = PhotonNetwork.Instantiate(playerPrefabFemale.name, new Vector3(73, 22, 34), Quaternion.identity); } else { spawnedPlayer = PhotonNetwork.Instantiate(playerPrefab.name, new Vector3(73, 22, 34), Quaternion.identity); } // 装备激活逻辑完全交给PlayerEquipment脚本处理,无需手动调用SetActive }
步骤3:关键注意事项
- 所有玩家预制体必须挂载
PhotonView组件,PlayerEquipment脚本继承MonoBehaviourPunCallbacks后会自动关联该组件。 - 所有可选装备(不同身体、护盾等)默认保持禁用状态,通过
ToggleSpecificEquipment方法按需激活。 - 禁止用静态类存储远程玩家的装备数据,必须通过Photon的RPC或玩家自定义属性传递装备信息(上述方案用RPC直接传递数据,也可将装备信息存入
PhotonNetwork.LocalPlayer.CustomProperties,其他客户端通过photonView.Owner.CustomProperties读取)。
内容的提问来源于stack exchange,提问作者dbulut
相关产品推荐
相关产品推荐

