Moving hit detection to the server

Our first order of business is to move the raycast function to the server.

We have a readymade solution for this—we can simply mark our Fire function as an RPC, and instead of calling it directly, we broadcast an RPC instead.

First, we'll modify our Fire function as follows:

[RPC]
void Fire()
{
  // this code should never execute on any machine other than the server/host
  if( !Network.isServer )
    return;

  RaycastHit hit;
  if( Physics.Raycast( transform.position, transform.forward, out hit, 100f, HitLayers ) )
  {
    // let a script on the object handle taking damage
    hit.collider.SendMessage( "TakeDamage", Damage, SendMessageOptions.DontRequireReceiver );
  }
}

We'll then send an RPC to call the Fire function rather than directly ...

Get Unity Multiplayer Games now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.