Hi all, I've been trying this over a few weeks now and just when I think the code's working, I see new issues develop. Briefly, I'm taking a screenshot of a particular area in my 3D game. The screenshot is accurate when I play it through the editor but when I deploy it to my devices, the displayed area shifts down. I've used Debug.Log to check the values for positions on both devices (and the editor) and they're all accurate. Could someone advice where I'm going wrong? For reference, I'm using an orthographic camera which is rotated on X by 28 degrees. Code (CSharp): int samplingFactor = 2; int yMin = (int)(Camera.main.WorldToScreenPoint (gameManager.horizonPoint.position)).y; int yMax = (int)(Camera.main.WorldToScreenPoint (gameManager.apexPoint.position)).y; int height = yMax - yMin; //create texture with the same scaling as the image Texture2D tex = new Texture2D (Screen.width * samplingFactor, height * samplingFactor, TextureFormat.RGB24, false); //render the entire screen into this texture RenderTexture snapshotRT = new RenderTexture (Screen.width * samplingFactor, Screen.height * samplingFactor, 24, RenderTextureFormat.ARGB32); RenderTexture.active = snapshotRT; Camera.main.targetTexture = snapshotRT; Camera.main.Render (); Rect captureRect = new Rect (0.0f, yMin * samplingFactor, (float) Screen.width * samplingFactor, (float) (height * samplingFactor)); tex.ReadPixels (captureRect, 0, 0); tex.Apply(); byte[] val = tex.EncodeToPNG(); //THIS IS WHERE I DISPLAY THE TEXTURE RenderTexture.active = null; Camera.main.targetTexture = null; Destroy (tex); Regards, Farooq
Dunno but you might want to put the function in a Coroutine and add some yield return new WaitForEndOfFrame() between creating the render texture, the render, and the readPixels function.
Oops - I didn't post the whole method. This method is called from a coroutine only after a yield return new WaitForEndOfFrame(). Thanks for the message.
I found this comment by atti at this link: http://answers.unity3d.com/questions/22954/how-to-save-a-picture-take-screenshot-from-a-camer.html So, I'm trying to see if aspect ratio is causing the problems at the point where I assigned the snapshotRT to the camera. Anyone has some idea if this could be the case?
So just in case someone's looking for something similar: I managed to fix this but it's still a little strange. I use the coordinate inversions i.e. rect start from 0,0 on the top-left and screen coordinates starting from 0,0 on the bottom left. After adjusting for this, the editor window shows the weird result I was getting on my device before but the device shows the screenshot accurately!
I think this could've been a Unity bug. I'm deploying now to iOS10 and have reverted back to the original code and it works. Just thought I'd drop an update for anyone looking for a solution.