我正在尝试使用ClientRpc
属性通过网络发送各种基本类型的数组。 documentation状态,我可以通过网络发送这些状态:
- 基本类型(byte,int,float,string,UInt64等)
- 基本类型数组
然而,似乎将它们混合在object[]
数组中是行不通的。我有以下示例:
[Command]
void CmdForwardEvent(string eventName, object[] args) {
Debug.Log ("Broadcasting event: " + eventName);
foreach (var o in args) {
Debug.Log ("arg-class: " + o.GetType() + ": " + o);
}
RpcForwardEvent (eventName, args);
}
[ClientRpc]
void RpcForwardEvent(string eventName, object[] args) {
Debug.Log ("Received event " + eventName);
foreach (var o in args) {
Debug.Log ("arg-class: " + o.GetType() + ": " + o);
}
}
void Update() {
if (Input.GetKeyDown (KeyCode.P)) {
CmdForwardEvent("Testevent", new object[]{"some string", 1, false});
}
}
在服务器上,我得到输出
Broadcasting event: Testevent
arg-class: System.String: some string
arg-class: System.Int32: 1
arg-class: System.Boolean: false
在客户端上,这没有任何错误地到达:
Received event: Testevent
arg-class: System.Object: System.Object
arg-class: System.Object: System.Object
arg-class: System.Object: System.Object
如何通过ClientRpc调用发送不同基本类型的各种参数?
答案 0 :(得分:1)
可能的解决方法是手动序列化数组并将其作为// new code
private BinaryFormatter bf = new BinaryFormatter();
private byte[] objectToBytes(object os) {
MemoryStream stream = new MemoryStream ();
bf.Serialize (stream, os);
return stream.ToArray ();
}
private object bytesToObject(byte[] bytes) {
MemoryStream stream = new MemoryStream (bytes);
return bf.Deserialize (stream);
}
// modified code:
[Command]
void CmdForwardEvent(string eventName, byte[] argsAsBytes) {
object[] args = bytesToObject(argsAsBytes) as object[]; // deserialize
Debug.Log ("Broadcasting event: " + eventName);
foreach (var o in args) {
Debug.Log ("arg-class: " + o.GetType() + ": " + o);
}
RpcForwardEvent (eventName, argsAsBytes);
}
[ClientRpc]
void RpcForwardEvent(string eventName, byte[] argsAsBytes) {
object[] args = bytesToObject(argsAsBytes) as object[]; // deserialize
Debug.Log ("Received event " + eventName);
foreach (var o in args) {
Debug.Log ("arg-class: " + o.GetType() + ": " + o);
}
}
void Update() {
if (Input.GetKeyDown (KeyCode.P)) {
// serialize
byte[] bytes = objectToBytes(new object[]{"some string", 1, false});
CmdForwardEvent("Testevent", bytes);
}
}
发送:
<input type="text" name="example" list="exList">
<datalist id="exList">
<option value="1">
<option value="2">
<option value="3">
<option value="4">
<option value="n">
</datalist>
客户端和服务器端的输出与预期的相同。