Search Unity

Graphics.CopyTexture then GetPixels

Discussion in 'General Graphics' started by CDF, Jul 11, 2017.

  1. CDF

    CDF

    Joined:
    Sep 14, 2013
    Posts:
    1,147
    Just going to assume that copying a RenderTexture to a Texture2D using CopyTexture doesn't give access to the pixel data on the Texture2D object?

    Because that's what I'm seeing. All color data, when using texture.GetPixel after the copy is:
    (0.804, 0.804, 0.804, 0.804)

    if I don't call texture.Apply() after the copy, then visualizing the texture in something like GUI.DrawTexture looks correct. However, after calling Apply, I can see the texture is just a semi-transparent white block.

    Guess I'll stick to RenderTexture.active if this is desired behaviour...
     
    AbleArcher likes this.
  2. Gizmoi

    Gizmoi

    Joined:
    Jan 9, 2013
    Posts:
    327
    I am also wondering about this.

    I am calling Graphics.CopyTexture to copy data from a RenderTexture to a Texture2D and then trying to use Get/SetPixels to manipulate the pixel data.
    Is this not allowed?
     
    AbleArcher likes this.
  3. grizzly

    grizzly

    Joined:
    Dec 5, 2012
    Posts:
    315
    Texture2D data can live in both CPU and GPU memory. Graphics.CopyTexture works on the GPU side while Set/GetPixels work on the CPU side. These copies are unsynchronised so changes made to one will not automatically appear in the other.
     
  4. Gizmoi

    Gizmoi

    Joined:
    Jan 9, 2013
    Posts:
    327
    So how do I get the pixel data from GPU memory to CPU memory?
     
  5. grizzly

    grizzly

    Joined:
    Dec 5, 2012
    Posts:
    315
    You can set your RenderTexture to be the active target and read from it. Something like this;
    Code (CSharp):
    1. RenderTexture.active = renderTexture;
    2. Texture2D tex = new Texture2D(renderTexture.width, renderTexture.height);
    3. tex.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
    4. tex.Apply();
     
  6. brianasu

    brianasu

    Joined:
    Mar 9, 2010
    Posts:
    369
    Just a warning this can be very slow because the GPU/CPU have to sync up.
     
    Covfefeh likes this.
unityunity