// (1) 스크린샷용 카메라를 준비합니다.
screenShotCamera.gameObject.SetActive(true);
// (2) 화면 크기를 지정합니다.
Vector2 screenSize = new Vector2(Screen.width, Screen.height);
// (3) 저장할 이미지의 크기를 지정합니다.(화면 크기 그대로 저장을 원하면 screenSize로 대체하시면 됩니다.)
Vector2 imageSize = new Vector2(
cat.pictureSize.x / cameraSize.x * screenSize.x,
cat.pictureSize.y / cameraSize.y * screenSize.y);
// (4) 저장할 이미지의 Offset을 지정합니다.
Vector2 imageOffset = cat.pictureOffset;
imageOffset.x += cameraSize.x * 0.5f - transform.position.x;
imageOffset.y += cameraSize.y * 0.5f - transform.position.y;
// (5) OpenGL의 경우 y축이 Upwards이고, 나머지의 경우 y축이 Downwards입니다.
if (SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.OpenGL2 &&
SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore &&
SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2 &&
SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3)
imageOffset.y = cameraSize.y - imageOffset.y;
imageOffset.x *= screenSize.x / cameraSize.x - imageSize.x * 0.5f;
imageOffset.y *= screenSize.y / cameraSize.y - imageSize.y * 0.5f;
// (6) RenderTexture에 screenShotCamera가 보고 있는 화면을 Render 합니다.
RenderTexture rt = new RenderTexture((int)screenSize.x, (int)screenSize.y, 32);
screenShotCamera.targetTexture = rt;
screenShotCamera.Render();
RenderTexture.active = rt;
// (7) RenderTexture를 Texture2D로 옮깁니다.
Texture2D cache = new Texture2D((int)imageSize.x, (int)imageSize.y, TextureFormat.ARGB32, false);
cache.filterMode = FilterMode.Bilinear;
cache.ReadPixels(new Rect(imageOffset, imageSize), 0, 0);
// (8) 저장합니다.
byte[] bytes = cache.EncodeToPNG();
string filename = Application.persistentDataPath + "/filename.png";
System.IO.File.WriteAllBytes(filename, bytes);
// (9) 뒷정리합니다.
screenShotCamera.targetTexture = null;
RenderTexture.active = null;
Destroy(rt);
screenShotCamera.gameObject.SetActive(false);