Search Unity

Resolved Serialize RenderTexture

Discussion in 'Netcode for GameObjects' started by CosmoM, Feb 14, 2022.

  1. CosmoM


    Oct 31, 2015
    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?
  2. CosmoM


    Oct 31, 2015
    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.

    Code (CSharp):
    1. public static class SerializationExtensions {
    2.     public static void ReadValueSafe(this FastBufferReader reader,out Texture2D texture) {
    3.         reader.ReadValueSafe(out int width);
    4.         reader.ReadValueSafe(out int height);
    5.         reader.ReadValueSafe(out byte[] byteArray);
    6.         texture=new Texture2D(width,height,TextureFormat.RFloat,false);
    7.         texture.Apply(false);
    8.         texture.LoadRawTextureData(byteArray);
    9.     } //ReadValueSafe
    11.     public static void WriteValueSafe(this FastBufferWriter writer,in Texture2D texture) {
    12.         int width=texture.width;
    13.         int height=texture.height;
    14.         byte[] byteArray=new byte[width*height*4];
    15.         System.Array.Copy(texture.GetRawTextureData(),byteArray,byteArray.Length);
    16.         writer.WriteValueSafe(width);
    17.         writer.WriteValueSafe(height);
    18.         writer.WriteValueSafe(byteArray);
    19.     } //WriteValueSafe
    20. } //SerializationExtensions
    Then in the object that has an array of RenderTextures (here called alphaTextures):

    Code (CSharp):
    1.     [ServerRpc]
    2.     public void SendAlphaTextureServerRpc(ulong clientId,int index) {
    3.         ClientRpcParams newClientRpc=new ClientRpcParams(){Send=new ClientRpcSendParams{TargetClientIds=new ulong[]{clientId}}};
    4.         Texture2D texture=new Texture2D(alphaResolution,alphaResolution,TextureFormat.RFloat,false);
    5.         texture.Apply(false);
    6.         Graphics.CopyTexture(alphaTextures,index,texture,0);
    7.         CopyAlphaTextureClientRpc(index,texture,newClientRpc);
    8.         Destroy(texture);
    9.     } //SendAlphaTextureServerRpc
    11.     [ClientRpc]
    12.     public void CopyAlphaTextureClientRpc(int index,Texture2D texture,ClientRpcParams clientRpcParams=default) {
    13.         Graphics.Blit(texture,alphaTextures,0,index);
    14.         Destroy(texture);
    15.     } //CopyAlphaTextureClientRpc
    Lyrcaxis likes this.