0

我有一个使用 Unity 的小型多人游戏。作为主机(名为 NiciBozz 的汽车),它看起来像这样: 主机视图

这很好,但作为客户端(这里名为 NiciBot),它看起来像这样: 客户视图

与用户名相关的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
[NetworkSettings(channel = 1, sendInterval = 0.2f)]

public class PlayerControll : NetworkBehaviour
{
    public Text Name;

    [SyncVar]
    public string playerName;

    private void Start()
    {
        if (isLocalPlayer)
        {
            CmdChangeName(PlayerPrefs.GetString("Name"));
        }
    }

    [Command(channel =1)]
    private void CmdChangeName(string name)
    {
        if (!isLocalPlayer)
        {
            Name.text = name;
            playerName = name;
            SetDirtyBit(1);
            return;
        }
        Name.text = name;
        playerName = name;
        SetDirtyBit(1);
    }
}

我应该怎么做才能正确同步用户名?

4

2 回答 2

0

使用带有命令的syncVar像这样:

   [SyncVar]//server to client. sync this variable name across all clients

   public string localPlayerName = "Player";

   void OnGUI()
    {
        if (isLocalPlayer)
        {
            localPlayerName = GUI.TextField(new Rect(0, 0, 100, 20), localPlayerName);

            if (GUI.Button(new Rect(110, 0, 100, 20), "Name"))
            {
                CmdUpdateLocalPlayerName(localPlayerName);

            }
        }
    }

    [Command]//client to server
    void CmdUpdateLocalPlayerName(string userName)
    {
        localPlayerName = userName;
    }
于 2017-03-25T06:13:06.733 回答
0

isLocalPlayer如果为真,您似乎只尝试设置名称,但CmdChangeName您有一个if检查值isLocalPlayer(将始终true基于您的代码段)。

CmdChangeName在别处打电话吗?

于 2017-02-24T10:00:12.780 回答