LoginSignup
70
64

More than 5 years have passed since last update.

Unityで画面のスクリーンショットを撮る(Application.CaptureScreenshotじゃない方法)

Last updated at Posted at 2016-05-27

最近リリースしたアプリ(チャリで来た。カメラ)で、画面のスクリーンショットを Application.CaptureScreenshot で取得してさらにその画像を加工する、ということを行ったのだが、もっと簡単な方法があったよ・・・(T_T)

Unityでスクリーンショットを撮る方法

Application.CaptureScreenshot

一番オーソドックスな方法。ファイル名を指定するだけでスクリーンショットをファイルに保存する。
実際アプリで使ってみたけど、意外と使いづらい。

  • パスではなくファイル名指定なので保存箇所が Application.persistentdatapath 1択
  • 「ファイルに保存される」「保存終了時のコールバックがない」ので、完成した画像をすぐに使いたい場合は待ち処理を組む必要がある

Render Texture

リアルタイムに更新可能なTexture「Render Texture」をTexture2Dとして取得する方法。
こっちの方が柔軟性はあるけど、Render Texture -> Texture2D への変換の手間や、uGUIと併用したりすると少し面倒。
ただ、この方法はカメラで映してるものをTextureとして出力するので、レイヤー分けが可能で、表示オブジェクトの制御が出来たりする(自由度は一番高い)。

Texture2D.ReadPixels

そしてこれ。

スクリーン画面からテクスチャデータへと保存するためのピクセルデータを読み込みます

これじゃんΣ(゚д゚;)!!
このメソッドがあることは知ってたけど、名前から予想出来なかったよ_| ̄|○

IEnumerator LoadScreenshot()
{
    yield return new WaitForEndOfFrame();

    var texture = new Texture2D(Screen.width, Screen.height);
    texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
    texture.Apply();
}

void OnPostRender()
{
    if(isCreate)
    {
        var texture = new Texture2D(Screen.width, Screen.height);
        texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        texture.Apply();

        isCreate = false;
    }
}

描画が完了してからでないとエラーが出るので、コルーチンで yield return new WaitForEndOfFrame() の後に処理するか、OnPostRender 内で行うと良い。

最後に

Texture2D.ReadPixels、静的メソッドでもないし、汎用的な名前だし、Texture2D.SetPixels と混同したりして、気づかなかった。。。
今までめっちゃメンドクサイことをしてたよ(´・ω・`)ショボーン

※追記

Render Texture を Texture2D として取得する方法も、最終的にはTexture2D.ReadPixels で読み込む形になるから、結局2通りって感じなのかな?テラシュールさんで「RenderTextureをTexture2DにしてSpriteに使用する」こんな方法も紹介されてたけど、あまり推奨してないようだし、素直に 単にスクショを撮りたい→Application.CaptureScreenshotスクショを加工したい→Texture2D.ReadPixelsって形になるかと。

70
64
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
70
64