コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】ランタイムで Texture の Read Write をオンにする例

概要

Texture の Read Write はランタイムでは変更できないが、
ランタイムで Texture を複製すれば、Read Write が Texture を使えるようになる

ソースコード

// 戻り値の Texture は不要になったら Destroy すること
private static Texture2D DuplicateTexture( Texture source )
{
    var width         = source.width;
    var height        = source.height;
    var renderTexture = RenderTexture.GetTemporary( width, height );
    var destination   = new Texture2D( width, height );

    Graphics.Blit( source, renderTexture );

    RenderTexture.active = renderTexture;

    destination.ReadPixels
    (
        source: new Rect( 0, 0, width, height ),
        destX: 0,
        destY: 0
    );

    destination.Apply();

    RenderTexture.active = null;
    RenderTexture.ReleaseTemporary( renderTexture );

    return destination;
}

参考サイト様