LoginSignup
8
4

More than 3 years have passed since last update.

Texture2DをC#ScriptでReadableに変更するには?

Last updated at Posted at 2019-07-11
texture2D.EncodeToPNG();

↑でいつもErrorになってしまう方へ。
Google先生に聞いても、答えは「Inspectorから操作して解決できる。」
いやいや、自分Scriptで解決したいんです:sweat_smile:
という方はお試しあれ:point_down:

・Console上のError

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

:angry: :angry: :angry: :angry: :angry: :angry:

・Unity公式では?

こちらをご覧ください。
いや、解決しないぞ:disappointed_relieved:

・対処方法

下記のメソッドを呼び出せばOK!

   Texture2D createReadabeTexture2D(Texture2D texture2d)
    {
        RenderTexture renderTexture = RenderTexture.GetTemporary(
                    texture2d.width,
                    texture2d.height,
                    0,
                    RenderTextureFormat.Default,
                    RenderTextureReadWrite.Linear);

        Graphics.Blit(texture2d, renderTexture);
        RenderTexture previous = RenderTexture.active;
        RenderTexture.active = renderTexture;
        Texture2D readableTextur2D = new Texture2D(texture2d.width, texture2d.height);
        readableTextur2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        readableTextur2D.Apply();
        RenderTexture.active = previous;
        RenderTexture.ReleaseTemporary(renderTexture);
        return readableTextur2D;
    }
呼び出し元
byte[] pngData = createReadabeTexture2D(notReadableTexture2D).EncodeToPNG();

もっと深くしりたい方は公式をどうぞ。

Texture関連をきちんと理解するとUnityでワンランクアップできますよ♪

8
4
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
4