'Unity How to CustomType to NetworkSerializable ,Transfer between Server and client
I custom serializable types String Array , learn:
and try it.
I Expect the result is:
<Server Received the RPC #0
#Test Server RPC#:a
Server Received the RPC #1
#Test Server RPC#:a
Server Received the RPC #2
...............................
But Real Rsult :
Server Received the RPC #0
#Test Server RPC#:a
Server Received the RPC #1
Server Received the RPC #2
Server Received the RPC #3
Can Tell me Why, Detail..
///////////////////////////////////////////////////////////////////////////
The code as below
using Unity.Netcode; using UnityEngine;
public class RpcTest : NetworkBehaviour {
private MyCustomStruct mystring;
public override void OnNetworkSpawn()
{
mystring.Array = new string[]{ "a", "b", "c" };
if (IsClient)
{
TestServerRpc(0,mystring);
}
}
[ClientRpc]
void TestClientRpc(int value, MyCustomStruct mystring)
{
if (IsClient)
{
Debug.Log("Client Received the RPC #" + value);
Debug.Log("#Test Client RPC#:" + mystring.Array[0].ToString());
TestServerRpc(value + 1, mystring);
}
}
[ServerRpc]
void TestServerRpc(int value, MyCustomStruct mystring)
{
Debug.Log("Server Received the RPC #" + value);
Debug.Log("#Test Server RPC#:" + mystring.Array[0].ToString());
TestClientRpc(value, mystring);
}
public struct MyCustomStruct : INetworkSerializable
{
public string[] Array;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
// Length
int length = 0;
if (!serializer.IsReader)
{
length = Array.Length;
}
serializer.SerializeValue(ref length);
// Array
if (serializer.IsReader)
{
Array = new string[length];
}
for (int n = 0; n < length; ++n)
{
serializer.SerializeValue(ref Array[n]);
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
