2017-02-24 53 views
0

我有一个与Unity的多人游戏。作为主机(汽车命名NiciBozz)它看起来像这样: Host viewUnity用户名不显示

这是好的,但作为一个客户端(这里命名NiciBot)它看起来像这样: Client View

相关的用户名的代码:

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); 
    } 
} 

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

回答

0

看来你只尝试设置的名称,如果isLocalPlayer是真实的,但在CmdChangeName你有一个if,检查的isLocalPlayer值(这将始终根据您的片断true)。

你在别处叫CmdChangeName吗?

+0

不可以,但它不会因为内容是相同的任何改变。 – NiciBozz

+0

那么这个“ASDFASDF”如何显示在汽车之上? –

+0

它是ui.text元素的默认文本 – NiciBozz

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; 
    }