如何使用Unity C#将字符串从对等服务器发送到客户端
本文关键字:服务器 客户端 对等 Unity 何使用 字符串 | 更新日期: 2023-09-27 18:26:40
我正在用C#用Unity引擎编程一个游戏。我希望用户充当服务器或客户端,也希望服务器能够向客户端发送消息(字符串)。我试过使用函数,但它当然不起作用,因为if有两个独立的身份。现在我正在尝试使用RCP,但它似乎不像教程中那样工作。。。。我在Update函数中得到一个编译器错误。我已经附加了"网络视图"组件。
using UnityEngine;
using System.Collections;
public class NetworkManager : MonoBehaviour
{
private int maxConnections = 12;
private int serverPort = 9955;
public string message = "NoMessageSelected";
public bool sendMessage = false;
public void OnGUI()
{
//Creates 2 Buttons on GUI, if disconnected
if (Network.peerType == NetworkPeerType.Disconnected)
{
if (GUI.Button (new Rect (100, 100, 100, 30), "Server"))
{
Network.InitializeServer (maxConnections, serverPort);
}
if (GUI.Button (new Rect (200, 100, 100, 30), "Client"))
{
Network.Connect ("localHost", serverPort);
}
}
////Shows Client or Server GUI
//Client
if (Network.peerType == NetworkPeerType.Client)
{
GUI.Label (new Rect (100, 100, 400, 30), "Connected to Server");
//Disconnect
if (GUI.Button (new Rect (200, 200, 100, 30), "Disconnect"))
{
Network.Disconnect();
MasterServer.UnregisterHost();
}
}
//Server
if (Network.peerType == NetworkPeerType.Server)
{
GUI.Label (new Rect (100, 100, 400, 30), "Clients connected: " +
Network.connections.Length);
message = GUI.TextField(new Rect(150, 150, 200, 20), message, 25);//How to
receive "message"?
//Sends message via RPC
if (GUI.Button (new Rect (200, 200, 100, 30), "Send Message"))
{
networkView.RPC ("PrintText", RPCMode.All, "Hello world");
}
}
}
public void Update()
{
Debug.Log (message);
}
@RPC
function PrintText (text : String)
{
Debug.Log(text);
}
}
您已经将JS函数声明复制到C#脚本中。你可以在这里看到所有三种语言的例子-http://docs.unity3d.com/ScriptReference/NetworkView.RPC.html
C#等价物:
[RPC]
public void PrintText (String text)
{
Debug.Log(text);
}