Search code examples
c#unity-game-enginephoton

How to correct call RPC on all clients?


I created simple script just for testing how RPC works, and cant understand one thing. Here is my code:

public class TestRPC : MonoBehaviour
{
    public static TestRPC Instance { get; private set; }

    [SerializeField]
    public static int Opp = 5;

    float timer = 2f;

    private void Awake()
    {
        if (Instance != null) return;
        else Instance = this;
    }

    [PunRPC]
    public void AddOpp(int add)
    {
        Opp += add;
    }

    void Update()
    {
        timer -= Time.deltaTime;
        if(timer <= 0)
        {
            Debug.LogError(Opp);
            timer = 2f;
        }
    }
}

what i expect: there is 2 players in the scene. After call RPC AddOpp should called twice and in Update method will be logged 15.

PhotonView.Get(FindObjectOfType<TestRPC>()).RPC("AddOpp", RpcTarget.All, new object[] { 5 });

I tried even use IPunObservable to sync Opp var, but in didnt help

    public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.IsWriting)
            stream.SendNext(Opp);
        if (stream.IsReading)
            Opp = (int)stream.ReceiveNext();
    }

it logged 10 anyway. So - how does RPC works or what i do wrong? Understanding of RPC would help me further create my game. Tnx

still 10


Solution

  • You have your 2 players, P1 and P2.

    Each player controls one instance in the scene.

    P1 has a remote controlled instance of P2 (controlled by player 2).
    P2 has a remote controlled instance of P1 (controlled by player 1).

    P1 makes its RPC call using RPCTarget.All:

    All remote (and local) instances of P1 on all connected clients receive that call.

    On P1's side, the value of 5 is added to the starting value of 5 making 10.
    On P2's side, that same call happens to the remote controlled instance of P1, with the same result.

    This call generates the debug output of 10 in the console for both players (from the P1 instances).

    P2 makes its RPC call using RPCTarget.All:

    All remote (and local) instances of P2 on all connected clients receive that call.

    On P2's side, the value of 5 is added to the starting value of 5 making 10.
    On P1's side, the same call happens to the remote controlled instance of P2, with the same result.

    This call also generates the debug output of 10 in the console for both players (from the P2 instances).

    Console Logs
    In the console for each player, you should see 10 (from P1's RPC call) and 10 (from P2's RPC call).