Search Unity

Render Texture garbage collection

Discussion in 'Scripting' started by Hermonirr, Oct 23, 2019.

  1. Hermonirr

    Hermonirr

    Joined:
    Dec 23, 2013
    Posts:
    56
    Hi,

    I'm sending the views from two cameras over a TCP connection. The cameras render to render textures, and I convert them to byte[] and send them:

    Code (CSharp):
    1.    
    2. IEnumerator SendTexture()
    3.     {
    4.         Debug.Log(gameObject.name + " In SendTexture(), sendingVideo = " + sendingVideo);
    5.        
    6.         readyToGetFrame = true;
    7.  
    8.         while (sendingVideo)
    9.         {
    10.             yield return new WaitForSeconds(1/fps);
    11.             //Wait for End of frame - Render Textures shouldn't be called before that
    12.             yield return waitEndOfFrame;
    13.  
    14.             // Get the images from the cameras to the textures
    15.             RenderTexture.active = depthRenderTexture;
    16.             depthTexture.ReadPixels(textureRect, 0, 0);
    17.  
    18.             RenderTexture.active = colorRenderTexture;
    19.             colorTexture.ReadPixels(textureRect, 0, 0);
    20.  
    21.             // Convert the textures to byte[]
    22.             colorBytes = colorTexture.GetRawTextureData();
    23.             depthBytes = depthTexture.GetRawTextureData();
    24.  
    25.  
    26.             readyToGetFrame = false;
    27.  
    28.             // Convert a 4 bytes per pixel array to one bytes per pixel
    29.             singleChannelDepthBytes = Utils.GetSingleChannelDepth(depthBytes);
    30.  
    31.             // Actually sending the textures
    32.                 Loom.RunAsync(() =>
    33.                 {
    34.                     timestamp = Utils.ToUnixTime(DateTime.UtcNow).ToString();
    35.                     timeStampBytes = Encoding.ASCII.GetBytes(timestamp);
    36.                     stream.Write(timeStampBytes, 0, timeStampBytes.Length);
    37.                    
    38.                     //Send the color image bytes
    39.                     stream.Write(colorBytes, 0, colorBytes.Length);
    40.  
    41.                     //Send the depth image bytes
    42.                     stream.Write(singleChannelDepthBytes, 0, singleChannelDepthBytes.Length);
    43.  
    44.                     //Sent. Set readyToGetFrame true
    45.                     readyToGetFrame = true;
    46.                 });
    47.             //Wait until we are ready to get new frame (Until we are done sending data)
    48.             while (!readyToGetFrame)
    49.             {
    50.                 yield return null;
    51.             }
    52.         }
    53.     }
    54.  
    The problem is that Garbage Collection allocates 5.6 MB each time this happens:

    upload_2019-10-23_14-25-11.png

    Any advice?

    Thanks