Unity version: 5.5
Scene example:
- Light [GameObject with a Light component]
- LightSwitch - [Contains: BoxCollider|NetworkIdentity|Script inherited from NetworkBehaviour that toggles light on/off when someone clicks over it's BoxCollider]
LightSwitch.cs
public class LightSwitch : NetworkBehaviour
{
public GameObject roomLight;
void OnMouseDown () {
CmdToggleLight(!roomLight.activeSelf);
}
[Command]
void CmdToggleLight (bool status) {
RpcToggleLight(status);
}
[ClientRpc]
void RpcToggleLight (bool status) {
roomLight.SetActive(status);
}
}
¿How can i let any player click that LightSwitch and toggle the lights on/off?
Edit: Following the example, this is the code that i had to build:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class LightSwitch : NetworkBehaviour
{
public GameObject roomLight;
[SyncVar(hook="setLight")]
private bool status;
void OnMouseDown()
{
// my player's singleton
Player.singleton.CmdToggleSwitch(this.gameObject);
}
public void toggleLight()
{
status = !status;
}
void setLight(bool newStatus)
{
roomLight.SetActive(newStatus);
}
[ClientRpc]
public void RpcToggleSwitch(GameObject switchObject)
{
switchObject.GetComponent<LightSwitch>().toggleLight();
}
}
Player.cs code:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Collections.Generic;
using System;
public class Player : NetworkBehaviour {
public static Player singleton;
void Start () {
singleton = this;
}
//... my player class code ....//
[Command]
public void CmdToggleSwitch(GameObject gObject)
{
gObject.GetComponent<LightSwitch>().RpcToggleSwitch(gObject);
}
}
A big piece of shit just to toggle a light, thanks to Unity.