ゲームが作れるようになるまでがんばる日記

ゲーム制作のことを中心にゲームに関することを書いています

Unityのレンダリング画像をファイルに出力

作成中のゲームのキャラクター画像をUnityで作成することにした。
kan-kikuchi.hatenablog.com
まず、この記事を参考にUnityのカメラ映像をRenderTextureを使って画像として取得できるようにした。
このときLayerを使ってキャラクターだけ取り出し、背景は透明になるようにした。
psychic-vr-lab.com
次のこの記事を参考にRenderTextureの画像をPNGファイルとして出力した。
プログラムをちょっと変更して、アルファ付きの画像を連番でファイル出力するようにした。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class SaveRenderTextureToPng : MonoBehaviour
{
    public RenderTexture RenderTextureRef;
    private int index = 0;

    void Start() { }

    void Update()
    {
        savePng(index++);
    }

    void savePng(int index)
    {
        Texture2D tex = new Texture2D(RenderTextureRef.width, RenderTextureRef.height, TextureFormat.RGBA32, false);
        RenderTexture.active = RenderTextureRef;
        tex.ReadPixels(new Rect(0, 0, RenderTextureRef.width, RenderTextureRef.height), 0, 0);
        tex.Apply();

        // Encode texture into PNG
        byte[] bytes = tex.EncodeToPNG();
        Object.Destroy(tex);

        //Write to a file in the project folder
        File.WriteAllBytes(Application.dataPath + "/../SavedScreen_"+index.ToString()+".png", bytes);
    }
}

これでキャラクターの画像ファイルを作成することができた。