Unity Networking - [command]函数在不应该

时间:2016-06-28 04:17:37

标签: c# networking unity3d unity3d-unet

我对团结网络和网络本身都很陌生。

游戏: 我有2个玩家多人游戏,每个玩家都可以拍摄。

问题:

代码1让两位玩家在主持人按空格键时进行拍摄(仅在主游戏中)。客户端播放器无法从客户端的游戏中进行拍摄。

注意:if (Input.GetKeyDown (KeyCode.Space))位于CmdShoot方法中。

代码2正确执行。主持人可以在主机游戏中进行拍摄,客户可以从客户端的游戏中进行拍摄。

注意:if (Input.GetKeyDown (KeyCode.Space))在代码2的CmdShoot方法之外。

问题: 在代码1中,为什么客户端无法进行拍摄?为什么主机会让两个玩家都拍摄?

代码1:

// Update is called once per frame
void Update () {
    if (!isLocalPlayer) {
        return;
    }

    CmdShoot ();
}

[Command]
void CmdShoot(){
    if (Input.GetKeyDown (KeyCode.Space)) {

        GameObject force_copy = GameObject.Instantiate (force) as GameObject;
        force_copy.transform.position = gameObject.transform.position + gameObject.transform.forward;
        force_copy.GetComponent<Rigidbody>().velocity = gameObject.transform.forward * force.GetComponent<Force>().getSpeed();

        NetworkServer.Spawn (force_copy);

        Destroy (force_copy, 5);
    }

}

代码2:

// Update is called once per frame
void Update () {
    if (!isLocalPlayer) {
        return;
    }
    if (Input.GetKeyDown (KeyCode.Space)) {
        CmdShoot ();
    }
}

[Command]
void CmdShoot(){

    GameObject force_copy = GameObject.Instantiate (force) as GameObject;
    force_copy.transform.position = gameObject.transform.position + gameObject.transform.forward;
    force_copy.GetComponent<Rigidbody>().velocity = gameObject.transform.forward * force.GetComponent<Force>().getSpeed();

    NetworkServer.Spawn (force_copy);

    Destroy (force_copy, 5);

}

1 个答案:

答案 0 :(得分:0)

[Command]标记告诉客户端想要在服务器上执行此功能。

在代码1的情况下,您的代码调用CmdShoot()在服务器上执行,然后检查服务器是否正在按住Space(因此只有主机可以拍摄所有内容而且客户端根本无法进行拍摄)。

在Code 2的情况下,您的代码首先检查本地程序是否按住Space键(独立于主机或客户端)。如果本地程序持有空格键,则它会调用服务器上的CmdShoot()