When a client connects to an ongoing game, part of the state of my game is captured in a RenderTexture, and so the client needs to receive one from the server. However, it’s not clear to me how to serialize it; does anyone know?
I worked out something that works, but only for small textures, otherwise they are too large to serialize at once. For my larger textures, I’ll try splitting up the byte array, but in case it’s useful to anyone, below is my code for serializing a RenderTexture – specifically, serializing a single RenderTexture out of an array. Note that I’ve hardcoded the texture format, but you don’t have to.
Anywhere:
public static class SerializationExtensions {
public static void ReadValueSafe(this FastBufferReader reader,out Texture2D texture) {
reader.ReadValueSafe(out int width);
reader.ReadValueSafe(out int height);
reader.ReadValueSafe(out byte[] byteArray);
texture=new Texture2D(width,height,TextureFormat.RFloat,false);
texture.Apply(false);
texture.LoadRawTextureData(byteArray);
} //ReadValueSafe
public static void WriteValueSafe(this FastBufferWriter writer,in Texture2D texture) {
int width=texture.width;
int height=texture.height;
byte[] byteArray=new byte[width*height*4];
System.Array.Copy(texture.GetRawTextureData(),byteArray,byteArray.Length);
writer.WriteValueSafe(width);
writer.WriteValueSafe(height);
writer.WriteValueSafe(byteArray);
} //WriteValueSafe
} //SerializationExtensions
Then in the object that has an array of RenderTextures (here called alphaTextures):
[ServerRpc]
public void SendAlphaTextureServerRpc(ulong clientId,int index) {
ClientRpcParams newClientRpc=new ClientRpcParams(){Send=new ClientRpcSendParams{TargetClientIds=new ulong[]{clientId}}};
Texture2D texture=new Texture2D(alphaResolution,alphaResolution,TextureFormat.RFloat,false);
texture.Apply(false);
Graphics.CopyTexture(alphaTextures,index,texture,0);
CopyAlphaTextureClientRpc(index,texture,newClientRpc);
Destroy(texture);
} //SendAlphaTextureServerRpc
[ClientRpc]
public void CopyAlphaTextureClientRpc(int index,Texture2D texture,ClientRpcParams clientRpcParams=default) {
Graphics.Blit(texture,alphaTextures,0,index);
Destroy(texture);
} //CopyAlphaTextureClientRpc
1 Like