所以我的问题是每当我尝试用一个按钮调用hostData数组时它返回null,但我知道它不是null。我甚至把一个debug.log调用update()中的HostData数组的第一个成员,并获取当hostData!= null时它返回每一帧但是每当我从按钮调用它时它都是null,我甚至使用if(hostData) == null)来验证它。什么可能导致这种情况?
private HostData[] hostData;
private bool refreshing = false;
private Text joinServerText;
private GameObject joinServerButton;
private GameObject startServerButton;
private GameObject refreshServerButton;
void Awake()
{
joinServerButton = GameObject.Find ("JoinServerButton");
joinServerText = GameObject.Find("JoinServerText").GetComponent<Text>();
startServerButton = GameObject.Find ("StartServerButton");
refreshServerButton = GameObject.Find ("RefreshServerButton");
}
void Start()
{
joinServerButton.SetActive (false);
}
void StartServer()
{
bool useNat = !Network.HavePublicAddress();
Network.InitializeServer(2,25000, !useNat);
MasterServer.RegisterHost(gameName,"Tutorial Game Name","This is a tutorial game");
}
void refreshHostList()
{
MasterServer.RequestHostList(gameName);
refreshing = true;
}
void Update()
{
if (refreshing)
{
if(MasterServer.PollHostList().Length > 0)
{
refreshing = false;
Debug.Log (MasterServer.PollHostList().Length);
hostData = MasterServer.PollHostList();
}
}
if(hostData != null)
{
joinServerButton.SetActive (true);
joinServerText.text = hostData[0].gameName;
Debug.Log ("hostData[0].gameName");
}
}
//Messages
void OnServerInitialized()
{
Debug.Log ("Server Initialized!");
}
void OnMasterServerEvent(MasterServerEvent mse)
{
if(mse == MasterServerEvent.RegistrationSucceeded)
{
Debug.Log ("Registered Server");
}
}
//UI
public void StartSeverButton()
{
Debug.Log ("Starting Server...");
StartServer();
}
public void RefreshHostsButton()
{
Debug.Log ("Refreshing Hosts...");
refreshHostList();
}
public void JoinServerButton()
{
//for(int i=0; i<hostData.Length; i++)
//{
if (hostData == null) <--------- My problem
{
Debug.Log("hostData is null");
//Debug.Log (hostData[0].gameName);
//Network.Connect (hostData[0]);
}
}
}
答案 0 :(得分:0)
我通常通过替换它来解决神秘的错误值分配问题:
private HostData[] hostData;
有了这个:
private HostData[] _hostData;
private HostData[] hostData { get { return _hostData; } set { _hostData=value; Debug.Log("Host data set. Is null?: "+(_hostData == null), this); } }
运行它,您将立即看到变量何时设置为null。也许你会发现问题不是你想的 - 例如,它可能永远不会被设置,并且实际上有该类的多个实例,以及打印主机的实例count不是具有null变量的同一实例。