Search Unity

Question Unity ServerRpc isn't getting called from client side

Discussion in 'Multiplayer' started by unitymaster1337, Aug 16, 2022.

  1. unitymaster1337

    unitymaster1337

    Joined:
    May 3, 2022
    Posts:
    1
    I'm a beginner in Unity and i tried to make basic multiplayer project following this guide:

    Player movement worked fine and then i started trying to implement hitscan shots mechanic. When i try to shoot the dummy from host side, it only executes effects in host's instance of the game, and when i try to shoot from client side, it doesn't even call next functions
    Code (CSharp):
    1. void FixedUpdate()
    2.     {  
    3.         //client tries to shoot
    4.         if (Input.GetMouseButton(0) && attackCD >= attackmaxCD)
    5.         {
    6.             RequestFireServerRpc(transform.position,transform.forward);
    7.             print("clicked");
    8.             attackCD = 0;
    9.         }
    10.         if (grounded)
    11.         {
    12.             rb.drag = grounDrag;
    13.         }else
    14.         {
    15.             rb.drag = 0;
    16.         }
    17.         mover.transform.Translate(deltamove);
    18.         attackCD += Time.deltaTime;
    19.     }
    20.     //message is sent to the server
    21.     [ServerRpc(RequireOwnership = false)]
    22.     private void RequestFireServerRpc(Vector3 spawnpos,Vector3 dir)
    23.     {
    24.         FireClientRpc(spawnpos,dir);
    25.         print("sent");
    26.     }
    27.     //server sends message to clients
    28.     [ClientRpc]
    29.     private void FireClientRpc(Vector3 spawnpos,Vector3 dir)
    30.     {
    31.         ExecuteShot(spawnpos,dir);
    32.         print("recieved");
    33.     }
    34.     //command gets executed at clients
    35.     void ExecuteShot(Vector3 spawnpos,Vector3 dir)
    36.     {
    37.         RaycastHit shot;
    38.         if (Physics.Raycast(spawnpos, dir, out shot))
    39.         {
    40.             if (shot.collider.tag == "Target")
    41.             {
    42.                 print("hit");
    43.                 Vector3 hit = shot.collider.transform.position - transform.position;
    44.                 shot.collider.GetComponent<Knockback>().TakeKnockback(hit, 10, 0.2f);
    45.                 Debug.DrawRay(transform.position, transform.forward, Color.red, 10);
    46.             }
    47.         }
    48.     }
    This is portion of the code dedicated to shooting. Shooting from host side prints all of the debug text, while shooting from client side only prints "clicked". Commentaries in code is how i think each step works. I have installed "Netcode for GameObject" and functions are called on NetworkBehaviour