统一版本:5.5
场景示例:
- Light [带有 Light 组件的游戏对象]
- LightSwitch - [包含:BoxCollider|NetworkIdentity|从 NetworkBehaviour 继承的脚本,当有人点击它的 BoxCollider 时打开/关闭灯光]
灯开关.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);
}
}
¿我怎样才能让任何玩家点击LightSwitch并打开/关闭灯?
编辑:按照示例,这是我必须构建的代码:
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 代码:
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);
}
}
多亏了 Unity,只是为了切换灯而已。