Syncing a Flashlight over the Network

Recently I have been attempting to get a flashlight to properly activate and deactivate on multiplayer. Each client has a flashlight, but due to my limited knowledge of unity networking and RPC’s, I have failed at getting each client to have control of only their flashlight and have it be synced throughout the network. This is my code after many different rewrites for the RPC.

#pragma strict
var lighttoggle : AudioClip;
var flashlightstate = true;
function Start () {

}

function Update () {
    if (Input.GetButtonDown("Flashlight")) {
         audio.volume = 1.0;
        light.enabled =! light.enabled;
        audio.PlayOneShot(lighttoggle);
        if (light.enabled){
        flashlightstate = true;
        }
        if (!light.enabled){
        flashlightstate = false;
        }

  if(!networkView.isMine)
  {
     enabled=false;
  }
 	}
}

function OnSerializeNetworkView(stream : BitStream, 
    info : NetworkMessageInfo) {

    if (stream.isWriting) {
        light.enabled = flashlightstate;
        stream.Serialize(light);
    } else {
        stream.Serialize(flashlightstate);
        light.enabled = flashlightstate;
    }    
}


Any assistance would be appreciated.

1 Answer

1

Something like this should work better:

    #pragma strict 
var lightToggle : AudioClip;

function Start()
{
	//assign an arbitrary group value. I personally use an enum for these
	networkView.group = 3;
}
    
function Update () 
{  
	if (Input.GetButtonDown("Flashlight")) 
	{  
		//we remove the last RPC to prevent the RPC buffer from getting bloated
		Network.RemoveRPCs(Network.player, 3); 
		networkView.RPC("ToggleFlashlightState", RPCMode.AllBuffered, !light.enabled);
	} 
}
    
@RPC
function ToggleFlashlightState()
{
	audio.volume = 1.0;  
	light.enabled = !light.enabled;  
	audio.PlayOneShot(lighttoggle); 
}

If you call the method locally (with a regular call, not an RPC) does it work? Does the Console give up any warnings or errors?