c# - 无法从客户端执行服务器命令

标签 c# unity3d

我正在尝试在玩家点击屏幕时生成子弹。当我在配对中创建服务器时,我可以生成子弹,我也可以在客户端看到它们。但是当我像客户端一样连接到服务器进行配对时,我无法产生子弹。我在服务器端收到此错误:

Found no behaviour for incoming [Command:InvokeCmdCmd_Fire] on Player(Clone) >(UnityEngine.GameObject), the server and client should have the same NetworkBehaviour instances [netId=2].
UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()

我的代码:

for (int x = 0; x < Input.touchCount; x++) 
        {
            touchpos = Camera.main.ScreenToWorldPoint(touch[x].position);
            if ((touchpos.x > -4.5f || touchpos.y > -1.2f))
            {
               pos = transform.position;

               if (magazine > 0)
                {
                    if (time > firetime && autoriffle)
                    {
                        Cmd_Fire();

                        time = 0;
                        magazine--;

                    }

        time += Time.deltaTime;

    }

    [Command]
    void Cmd_Fire()
    {      
        GameObject bullet = Instantiate(bulet, pos, Quaternion.FromToRotation(Vector3.up, new Vector3(touchpos.x, touchpos.y, transform.position.z) - transform.position)) as GameObject;

        bullet.GetComponent<Rigidbody>().AddForce(bullet.transform.up * bulletspeed, ForceMode.Impulse);

        NetworkServer.Spawn(bullet);

        // I try NetworkServer.SpawnWithClientAuthority(bullet, connectionToClient); too but same reason
    }

我的播放器预制件上有这个脚本。我添加了播放器和子弹预制网络身份和网络转换。在播放器上,我检查了本地播放器权限。

我还尝试创建一个新项目,将官方 Unity 多人网络教程中的所有内容都放在其中,但它也没有用。

感谢您的帮助。

最佳答案

我想通了。如果它没有附加到本地播放器,我正在销毁这个脚本。我应该只做-

if(!isLocalPlayer)
   return;`

不是

if(!isLocalPlayer)
{
   Destroy(this);
   return;
}

关于c# - 无法从客户端执行服务器命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41832720/

相关文章:

c# - 如何在不发送消息的情况下测试我的电子邮件设置?

c# - 获取安卓版本信息

c# - unity EditorGUI.PropertyField 无法完全禁用数组或列表

c# - 扩展方法中的协程

c# - 找不到 ASP.NET IserviceCollection AddIdentity

c# - ASP.Net "Access to the path ' ' 被拒绝。“文件上传控件在 Web 服务器 (IIS7) 中不起作用

c# - 将消息从存储过程返回到 C# 应用程序

c# - LINQ to Entities 无法识别该方法

c# - 使用 RX (Reactive Extensions) 创建 20 个延迟 30 毫秒的事件

c# - Unity计算3D鼠标位置