首页 > 解决方案 > Unity3D为什么我的客户端不能调用cmd方法?

问题描述

我的问题是:我有一个包含武器对象的玩家,我的武器对象包含以下脚本:

private void FixedUpdate()
{
    AutomaticFirearmShoot();
}


public void AutomaticFirearmShoot()
{
    if (Input.GetButton("Fire1") && Time.time > _nextFire)
    {
        _nextFire = Time.time + _fireRate;      
        _player.GetComponent<NetworkShootManager>().CmdShoot();

    }

}

我的根播放器也包含这个脚本:

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

public class NetworkShootManager : NetworkBehaviour
{
private void Update()
{
    if (!isLocalPlayer)
    {
        return;
    }
}

[Command]
public void CmdShoot()
{

   Debug.Log("shooting");

}


}

所以当我构建游戏时,只有宿主玩家可以调用该CmdShoot方法。

另外,我的播放器有网络身份组件。

标签: c#unity3dnetworking

解决方案


您应该可以使用Networking.NetworkBehaviour.isServer(已过时)来执行此操作。

实现可能是这样的:

[Command]
public void CmdShoot()
{

   if(!isServer)
       return; // If this is not being executed by the hoster then exit the method call.

   Debug.Log("shooting");

}

希望这可以帮助!


推荐阅读