Search Unity

Converting Texture To Texture2d And Getpixels

Discussion in 'Scripting' started by adrendaloth, Apr 10, 2019.

  1. adrendaloth

    adrendaloth

    Joined:
    Apr 5, 2019
    Posts:
    2
    I need to get the average color of a Texture generated at runtime (actually the video background of Vuforia camera). To do that, I converted this Texture to a Texture2D using a script found on this forum:
    Code (CSharp):
    1.    Texture mainTexture = renderer.material.mainTexture;
    2.               Texture2D texture2D = new Texture2D(mainTexture.width, mainTexture.height, TextureFormat.RGBA32, false);
    3.  
    4.               RenderTexture currentRT = RenderTexture.active;
    5.  
    6.               RenderTexture renderTexture = new RenderTexture(mainTexture.width, mainTexture.height, 32);
    7.               Graphics.Blit(mainTexture, renderTexture);
    8.  
    9.               RenderTexture.active = renderTexture;
    10.               texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
    11.               texture2D.Apply();
    12.  
    13.               Color[] pixels = texture2D.GetPixels();
    14.  
    15.               RenderTexture.active = currentRT;
    This works fine on editor but when testing it on an android device, GetPixels() only returns a red color value, blue and green ones remain 0. Yet, the texture is clear, the only thing is that it is shown on a redscale.
    I thought it could come from an unsupported texture format but I have not been able to find any information about that.
    Does anyone know the reason for which it happens?
     
  2. adrendaloth

    adrendaloth

    Joined:
    Apr 5, 2019
    Posts:
    2
    After some more research, I suspect this problem to come from the Blit() function because my renderTexture has already turned red. However, I still can't find on which point as the texture formats are the same on both editor and mobile, and I haven't found any other thread about it. Isn't there an alternative to this function to convert a Texture to a RenderTexture?