所以我正在学习与Unity建立联系,在阅读了一些文档并查看示例后,我最终得到了以下代码。每当我运行程序(使用Build& Run)并按下按钮来托管服务器时,我会收到消息“正在初始化...”,但它从未说过“服务器就绪:玩家连接。”。对我而言,这意味着服务器无法以某种方式初始化,但我真的不知道。其他的东西:即使它说“正在初始化......”我可以将鼠标悬停在其他按钮上并点击它们,这样程序就不会被冻结。此外,我第一次运行它时,我必须允许它通过我的防火墙,我做了。我只是试图通过局域网来实现这一点,我不关心用这个来上网。
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Net;
using System.Net.Sockets;
public class NetworkTestScript : MonoBehaviour
{
private string Address = "127.0.0.1";
private int PlayerCount = 0;
private float NextUpdate = 0.0F;
public NetworkPlayer Player;
public float UpdateInterval = 0.1F;
public GameObject Canvas;
public Text[] Texts;
void Start()
{
Canvas = GameObject.Find("Canvas");
Texts = Canvas.GetComponentsInChildren<Text>();
IPHostEntry Host;
Host = Dns.GetHostEntry(Dns.GetHostName());
foreach(IPAddress IP in Host.AddressList)
{
if(IP.AddressFamily == AddressFamily.InterNetwork)
{
Address = IP.ToString();
}
}
}
void Update()
{
if(Network.isClient && Time.realtimeSinceStartup > NextUpdate)
{
NextUpdate = Time.realtimeSinceStartup + UpdateInterval;
//If there is input, send it in RPC to server, which then sends it as an RPC to other players
}
}
public void StartServer()
{
Network.InitializeServer(2, 25000, false);
Texts[2].text = "Initializing...";
}
public void Connect()
{
Network.Connect(Address, 25000);
Texts[3].text = "Connecting...";
}
void OnConnectedToServer()
{
Texts[3].text = "Connected.";
Debug.Log("Connected to server.");
}
void OnFailedToConnect(NetworkConnectionError Error)
{
Texts[3].text = "Connection failed.";
Debug.Log("Connection failed: " + Error);
}
void OnSeverInitialized()
{
Debug.Log("Server initialized.");
Texts[2].text = "Server Ready: " + PlayerCount + " players connected.";
}
void OnPlayerConnected(NetworkPlayer P)
{
PlayerCount++;
NetworkViewID ViewID = Network.AllocateViewID();
Texts[2].text = "Server Ready: " + PlayerCount + " players connected.";
if(PlayerCount == 2)
{
Texts[2].text = "Players ready. Starting...";
}
Debug.Log("Player " + ViewID.ToString() + " connected from " + P.ipAddress + ":" + P.port);
}
void OnPlayerDisconnected(NetworkPlayer P)
{
PlayerCount--;
Texts[2].text = "Server Ready: " + PlayerCount + " players connected.";
Debug.Log("Player disconnected: " + P.ToString());
//Halt game
}
}