PhotonView不存在警告排查:双人射击游戏子弹销毁异常
问题分析与解决方案
警告原因
你遇到的Received RPC "RPCname" for viewID 2010 but this PhotonView does not exist!警告,核心原因是使用了RpcTarget.AllBuffered发送销毁RPC。这个目标会将RPC存入房间的全局缓冲区,即使子弹已经被销毁,后续加入房间的玩家或同步过程中,服务器仍会尝试向不存在的PhotonView发送该RPC,从而触发警告。此外,当前代码中存在非子弹拥有者调用销毁RPC的场景,也会导致重复触发无效指令。
修复步骤
- 替换RPC目标类型:将
RpcTarget.AllBuffered改为RpcTarget.All,子弹是临时对象,不需要缓冲销毁指令,All只会向当前在线的所有客户端发送一次RPC。 - 仅允许拥有者调用销毁RPC:子弹的销毁逻辑应该由创建它的客户端(即
PV.IsMine为true的端)触发,避免非拥有者重复调用。 - 使用PhotonNetwork销毁方法:用
PhotonNetwork.Destroy(gameObject)替代Unity原生的Destroy(gameObject),该方法会同步销毁所有客户端的对象,并自动清理PhotonView的注册信息,避免残留无效视图ID。 - 优化碰撞触发逻辑:合并碰撞判断条件,避免重复触发RPC。
修改后的代码
using Photon.Pun; using UnityEngine; public class Bullet : MonoBehaviour { private PhotonView PV; private int dir; void Awake() { PV = GetComponent<PhotonView>(); } void Start() { // 仅在拥有者端设置自动销毁,避免多端重复销毁 if (PV.IsMine) { Invoke(nameof(SelfDestroy), 10f); } } void OnTriggerEnter2D(Collider2D col) { // 仅允许拥有者处理碰撞销毁逻辑,避免多端重复发送RPC if (!PV.IsMine) return; bool shouldDestroy = false; if (col.CompareTag("Border")) { shouldDestroy = true; } else if (col.CompareTag("Player") && !col.GetComponent<PhotonView>().IsMine) { // 向被击中玩家的拥有者发送Hit RPC,保证只有玩家自身端处理受伤逻辑 col.GetComponent<PhotonView>().RPC("Hit", RpcTarget.Owner); shouldDestroy = true; } if (shouldDestroy) { PV.RPC("DestroyRPC", RpcTarget.All); } } [PunRPC] void DirRPC(int dir) => this.dir = dir; [PunRPC] void DestroyRPC() { // 使用PhotonNetwork的销毁方法清理视图,避免残留无效ID if (PV != null) { PhotonNetwork.Destroy(gameObject); } } void SelfDestroy() { if (PV.IsMine) { PV.RPC("DestroyRPC", RpcTarget.All); } } }
额外说明
- 被击中玩家的
Hit()方法需改为通过RPC调用(示例中col.GetComponent<PhotonView>().RPC("Hit", RpcTarget.Owner)),只有玩家的拥有者端应该处理自身受伤逻辑,避免同步冲突。 - 自动销毁逻辑仅在拥有者端执行,防止多端重复触发销毁RPC。
内容的提问来源于stack exchange,提问作者이관우
相关产品推荐
相关产品推荐

