Error with spawning gun gameobject in Photon Pun 2

So I have an inactive gun object as a child of the player, and when i activate the gun object this message shows upp, but only when there’s another player in the room. (im using photon pun2)

Caught exception in OnEvent() for event code 200: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.

UnityEngine.Debug:LogError (object)

Photon.Realtime.LoadBalancingClient:smile:ebugReturn (ExitGames.Client.Photon.DebugLevel,string) (at Assets/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:2564)

ExitGames.Client.Photon.PeerBase/<>c__DisplayClass108_0:b__0 () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PeerBase.cs:1212)

ExitGames.Client.Photon.EnetPeer:smile:ispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/EnetPeer.cs:440)

ExitGames.Client.Photon.PhotonPeer:smile:ispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PhotonPeer.cs:1771)

Photon.Pun.PhotonHandler:smile:ispatch () (at Assets/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:221)

Photon.Pun.PhotonHandler:FixedUpdate () (at Assets/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:147)

I think this is where the problem occures.

void GiveGun()
    {
        Player[] players = FindObjectsOfType<Player>();
        float furthestDistance = 0;
        Player playerToGetWeapon = null;
        for (int i = 0; i < players.Length; i++)
        {
            float distance = Vector2.Distance(players[i].transform.position, goal.position);
            if (distance > furthestDistance)
            {
                furthestDistance = distance;
                playerToGetWeapon = players[i];
            }
        }
        photonView.RPC("SpawnGun", RpcTarget.AllBuffered, playerToGetWeapon.GetInstanceID());       
    }

    [PunRPC]
    void SpawnGun(int instanceID)
    {
        Player player = GameObject.Find("Player" + instanceID).GetComponent<Player>();
        player.gun.gameObject.SetActive(true);
    }

Can someone please help me with this? Also I should mention that the game works as it should, I have no idea why the error shows up.

same issue

Hello,

An exception was thrown in your RPC function. I suggest you to put a breakpoint in your SpawnGun function and check if anything would throw a NullRefException. Your line 21 should also be separated in two lines that way :

GameObject playerGO = GameObject.Find("Player" + instanceID);
Player player = playerGO.GetComponent<Player>();

This would help you identify any issue.
An other suggestion would be to not use GameObject.Find as it takes a lot of time and resources to perform, and may return nothing in several cases, but that is an other discussion.

Try first to handle exceptions in your RPC.

1 Like