Unet Syncing Flashlights

Hello everyone! I’m in need of a little help. I need to be able to sync a flashlight to all the clients. example Each player has a flashlight someone turns there flashlight off. And everyone else can see that there flashlight is now off. My code right now is.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class flashlight : NetworkBehaviour {

    public bool IsOn;

    public Light MyLight;

    private void Start()
    {
        IsOn = true;
    }

    void Update () {

        if (Input.GetKeyDown(KeyCode.F) && isLocalPlayer)
        {
            IsOn = !IsOn;
            CmdLight();
            Debug.Log("Key Pressed");
        }
    }

    [Command]
    public void CmdLight()
    {
        Debug.Log("Command Recieved");

        if (IsOn)
        {
            RpcsyncFlashlight(true);
        }
        else
        {
            RpcsyncFlashlight(false);
        }
    }

    [ClientRpc]
    private void RpcsyncFlashlight(bool isOn)
    {
        MyLight.enabled = isOn;
        Debug.Log("RPC sent");
    }
}

Right now only the host can sync his flashlights to the on and off state. But other clients are unable to do so. Any help is appreciated.

P.S the host uses all 3 Debug.Log’s but the client only uses the last two. The client seems to not be able to detect the key press but when i press that key anyway it works but doesint print or change the value it just runs the command.

Ok i fixed it. If anyone wants to see the code used to fix it here you go :smiley:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class flashlight : NetworkBehaviour {

    [SyncVar]
    public bool IsOn;

    public Light MyLight;

    void Update () {

        if (!isLocalPlayer)
            return;

        if (Input.GetKeyDown(KeyCode.F))
        {
            IsOn = !IsOn;
            CmdLight(IsOn);
            Debug.Log("Key Pressed");
        }
    }

    [Command]
    public void CmdLight(bool test)
    {
        Debug.Log("Command Recieved");
        RpcsyncFlashlight(test);
    }

    [ClientRpc]
    private void RpcsyncFlashlight(bool isOn)
    {
        MyLight.enabled = isOn;
        Debug.Log("RPC sent");
    }
}

All i did was call a bool on the COMMAND.

You just saved my life, i finally understood how to use this!!

Hi,

Yeah same, now i understand RPC call, this was the first clear example what i found XD thx a lot.,Hi,
Yeah same, now i understand RPC call XD thx a lot