Search Unity

ReadPixel don't read the data from the camera it's attached to

Discussion in 'Scripting' started by SmokyZebra, Jan 28, 2015.

  1. SmokyZebra

    SmokyZebra

    Joined:
    Mar 13, 2014
    Posts:
    139
    Hello, i'm working on my character creation screen. I need to take a picture of one camera to use as an icon for the character in game. The trouble i have is that i manage to take a pic and save it to png but the content of the pic is not what i expect. There is one camera for the background, one camera for the GUI, one camera for the character and one last for the portrait of the character. The script is attached to that camera but in the png i get it shows what the first camera would show, the background, wich is not even on culling mask of the camera i use to take the picture.
     
  2. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    ReadPixels(...) doesn't read pixels from a Camera. Cameras don't own pixels.

    Cameras write either to the video buffer (the screen) or to a RenderTexture. ReadPixels(...) reads from the video buffer or the current active render texture (from memory check the docs) at the time it is called, so simply attaching it to a Camera does not ensure that what it reads is what that Camera rendered.

    However... MonoBehaviour has an OnPostRender method which, if attached to a Camera, will get called immediately after that camera has finished its rendering. So if you do your ReadPixels(...) in there you can make it happen immediately after the desired Camera has rendered, which should get what you're after.
     
  3. SmokyZebra

    SmokyZebra

    Joined:
    Mar 13, 2014
    Posts:
    139
    Hmm I'm already calling the readpixel from OnPostRender, but it does not work as intended :/
     
  4. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    Ahh. In that case are the clear flags set appropriately? Is it targeting a RenderTexture (though I assume not)?

    If you enable the camera, can you see what it's rendering and is that what you expect?
     
  5. SmokyZebra

    SmokyZebra

    Joined:
    Mar 13, 2014
    Posts:
    139
    Yeah the camera render well what i want on the screen, but when i take a picture i get what is behind what this camera actually see and what is on screen. It is not targeting a render texture.
     
  6. SmokyZebra

    SmokyZebra

    Joined:
    Mar 13, 2014
    Posts:
    139
    When i say what is behind what this camera see i actually mean that this camera have a depth higher than the one from wich i in the end get the data on my png.
     
  7. SmokyZebra

    SmokyZebra

    Joined:
    Mar 13, 2014
    Posts:
    139
    OK I've found out the problem, i made a mistake and was not giving the good coordinate in the Rect, resulting in the pic taken somewhere else on the screen, it works like a charm now that i've corrected this.
     
    angrypenguin likes this.