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 calling it:
void Update() { if( networkView.isMine && Input.GetMouseButtonDown( 0 ) ) { // if we're the server, just directly call the function // remember, server cannot use RPCMode.Server, the RPC is...