我想生成一个客户端和服务器都可以看到的弹跳球。 当客户连接并且下一个场景(球在弹跳的地方)被加载时,必须产生球。
问题是OnPlayerConnected()方法没有被调用,有没有人知道任何替代方案以及它为什么不起作用?
public class MainMenu : MonoBehaviour {
public string connectionIP = "127.0.0.1";
public int connectionPort = 25001;
bool isClientConnected = false;
void Awake()
{
// Make sure list is empty and request a new list
MasterServer.RequestHostList("MyUniqueGameType");
}
// Use this for initialization
void OnGUI()
{
HostData[] data = MasterServer.PollHostList ();
// Go through all the hosts in the host list
foreach (var element in data)
{
//Debug.Log ("server found");
GUILayout.BeginHorizontal ();
var name = element.gameName + " " + element.connectedPlayers + " / " + element.playerLimit;
GUILayout.Label (name);
GUILayout.Space (5);
string hostInfo;
hostInfo = "[";
foreach (var host in element.ip)
hostInfo = hostInfo + host + ":" + element.port + " ";
hostInfo = hostInfo + "]";
GUILayout.Label (hostInfo);
GUILayout.Space (5);
GUILayout.Label (element.comment);
GUILayout.Space (5);
GUILayout.FlexibleSpace ();
if (GUI.Button (new Rect (10, 30, 120, 20), "Client Connect"))
{
Network.Connect (connectionIP, connectionPort);
isClientConnected = true;
Application.LoadLevel ("scene1");
// Debug.Log ("spawning ball");
// SpawnBall();
}
GUILayout.EndHorizontal ();
}
if (GUI.Button (new Rect (10, 50, 120, 20), "Initialize Server"))
{
Network.InitializeServer (2, connectionPort, !Network.HavePublicAddress ());
// Network.InitializeServer (2, 25002, !Network.HavePublicAddress ());
MasterServer.RegisterHost ("MyUniqueGameType", "JohnDoes game", "l33t game for all");
/*
while(!isClientConnected)
{
Debug.Log("waiting for client");
}
*/
Application.LoadLevel("scene1");
}
}
void OnPlayerConnected(NetworkPlayer player)
{
Debug.Log ("OnPlayerConnected");
SpawnBall();
}
void SpawnBall()
{
GameObject objPrefab = Resources.Load("Ball") as GameObject;
GameObject obj = Instantiate(objPrefab) as GameObject;
}
答案 0 :(得分:1)
加载新场景时,此脚本将停止执行。因此,永远不会在客户端或服务器上调用消息处理程序OnPlayerConnected
。
您可以做的是使用RPC(远程过程调用)让客户端在连接并加载场景时通知服务器(这将在第二个场景中):
void Start() {
if(Network.isClient) {
networkView.RPC("SpawnBall", RPCMode.AllBuffered)
}
}
[RPC]
void SpawnBall(NetworkViewID viewID, Vector3 location) {
GameObject objPrefab = Resources.Load("Ball") as GameObject;
GameObject obj = Instantiate(objPrefab) as GameObject;
}
现在当客户端加载场景时,他会向服务器发送一个RPC,告诉他产生一个球。请注意Start
函数中我使用Network.isClient
指定只在客户端加载场景时才执行此代码。 RPCMode.AllBuffered
会将RPC发送给所有连接的播放器,包括发送它的客户端。
RPC是一种有价值的工具,如果在Unity中进行网络连接,您应该熟悉它们。