O'Reilly logo

Unity Multiplayer Games by Alan Stagner

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required