LoginSignup
8
11

More than 5 years have passed since last update.

RenderTextureを保存すると暗くなる問題【※Unity5.4.2p4現在】

Last updated at Posted at 2016-11-21

はじめに…

Unityでスクリーンショットを取る場合…

  1. Application.CaptureScreenshot
  2. Texture2DをエンコードしてFile.WriteAllBytesで書き込む

この二通りがあるかと思います。
今回は、保存先を指定するために2の方法で保存します。

暗くなる保存方法

  1. ProjectViewでRenderTextureを作成します
  2. 撮影したいCameraにRenderTextureを登録します
  3. 下記ソースコードのように実装します
ScreenShot.cs
Texture2D tex = new Texture2D(RenderTextureRef.width, RenderTextureRef.height, TextureFormat.RGB24, false);
RenderTexture.active = RenderTextureRef;
tex.ReadPixels(new Rect(0, 0, RenderTextureRef.width, RenderTextureRef.height), 0, 0);
tex.Apply();

//PNGに変換
byte[] bytes = tex.EncodeToPNG();
Object.Destroy(tex);

//保存
File.WriteAllBytes(Application.dataPath + "Hoge" + ".png", bytes);

これで保存した画像がコチラ

20161121210107.png

最初は、こういうもんなのかな?と思ってたんですが、違うみたいです。

暗くならない保存方法

  1. 下記ソースコードのように実装します
ScreenShot.cs
//プレビュー用のレンダーテクスチャからサイズ取得
int resWidth  = RenderTextureRef.width;
int resHeight = RenderTextureRef.height;

//RenderTextureを作る
RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
rt.antiAliasing = 8;

//Cameraに設定
camera.targetTexture = rt;
Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
camera.Render();
RenderTexture.active = rt;

//結果を読み込み
screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
camera.targetTexture = null;
RenderTexture.active = null; // JC: added to avoid errors

//破棄
Destroy(rt);

//PNGに変換
bytes = screenShot.EncodeToPNG();

//保存
File.WriteAllBytes(Application.dataPath + "Hoge" + ".png", bytes);

これで保存した結果がコチラ

20161121210107_02.png

本来の色で保存されています。

まとめ…

Unity5.4.2p4現在では、new RenderTextureで保存する方が良さそうです。
何か別の方法で解決した方がいましたら、教えていただけると幸いです。

8
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
11