うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】Texture2D の Read/Write Enable を変更せずに GetPixel する

通常 Texture2D からピクセル情報を取得する場合には、Read/Write Enable を true にする必要があります

こうしないと以下のエラーが出てしまします

UnityException: Texture 'Hoge' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings.

しかし、以下のようにTexture2D のコピーを行い、コピーしたテクスチャから GetPixel を呼び出す場合は

設定を変える必要が無くピクセル情報を取得することができます

public Color[,] ReadPixels(Texture2D texture)
{
    _cacheColors = new Color[texture.width, texture.height];
    var copyTexture = new Texture2D(texture.width, texture.height, texture.format, false);
    // テクスチャのコピー
    Graphics.CopyTexture(texture, copyTexture);

    for (var x = 0; x < _width; x++)
    {
        for (var y = 0; y < _height; y++)
        {
            _cacheColors[x, y] = copyTexture.GetPixel(x, y);
        }
    }
    return _cacheColors;
}

但し、Texture の Format が Automatic の場合は以下のエラーが発生してしまうため
RGBA32bit あたりにしておくとエラーが発生しません

Unsupported GraphicsFormat(47) for SetPixel operations.

f:id:hacchi_man:20211209002011p:plain