Search code examples
unity-game-enginerpcmultiplayerunity-networking

Unity Netcode's ClientRpc is not being sent across the network


I copy and pasted Unity Netcode's example code from https://docs-multiplayer.unity3d.com/docs/advanced-topics/message-system/clientrpc to test it out. This is my exact code:

public class Test : MonoBehaviour
{
    public TMP_Text text;
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.P))
        {
            PongClientRpc(Time.frameCount, "hello, world"); // Server -> Client
        }
    }
    [ClientRpc]
    void PongClientRpc(int somenumber, string sometext)
    {
        text.text = $"{somenumber} : {sometext}";
        Debug.Log(text.text);
    }
}

What I've found is that the function just acts as a normal function whether it's called on the host application or client application, and it is never transmitted across the network. My expectation is that when it is called on the host application, the RPC would be transmitted to the client application and executed there as well, thus reflecting a change in the TMP_Text object, but clearly this is not the case.

Just to check all the boxes, this script is attached to a GameObject that also has a NetworkObject component. For good measure, I tested the TMP_Text object both with and without a NetworkObject component attached. In all cases, any object with a NetworkObject component was properly added to the NetworkManager's network prefabs list.

I'm starting to question if I even understand what an RPC is or how it's supposed to work. Any insights would be greatly appreciated!


Solution

  • This class needs to be derived from NetworkBehavior not MonoBehaviour else it won't be networked.

    Make sure to add using Unity.Netcode; at the top of the class.