LoginSignup
0
0

More than 3 years have passed since last update.

Unityのテクスチャ

Last updated at Posted at 2021-04-22

Unity】Texture を Texture2D に変換する拡張メソッド

using UnityEngine;

public static class TextureExt
{
    public static Texture2D ToTexture2D( this Texture self )
    {
        var sw = self.width;
        var sh = self.height;
        var format = TextureFormat.RGBA32;
        var result = new Texture2D( sw, sh, format, false );
        var currentRT = RenderTexture.active;
        var rt = new RenderTexture( sw, sh, 32 );
        Graphics.Blit( self, rt );
        RenderTexture.active = rt;
        var source = new Rect( 0, 0, rt.width, rt.height );
        result.ReadPixels( source, 0, 0 );
        result.Apply();
        RenderTexture.active = currentRT;
        return result;
    }
}

Unityのテスクチャコピー(deep)

    {
        //参照だとダメ
        //      m_materials[name_list_curr].mainTexture = m_updatetex2d;

        //ConvertTextureはダメ: 何も表示されない
        //Graphics.ConvertTexture(m_updatetex2d, m_materials[name_list_curr].mainTexture);

        // CopyTextureはdeepcopy:何も表示されない
        //Graphics.CopyTexture(m_updatetex2d, m_materials[name_list_curr].mainTexture);

        //SetPixelsによるdeepcopy
        if (true)
        {
            var originalTexture = m_updatetex2d;
            Texture2D copyTexture = new Texture2D(originalTexture.width, originalTexture.height, TextureFormat.ARGB32, false);
            copyTexture.SetPixels32(originalTexture.GetPixels32());
            copyTexture.Apply();
            m_materials[name_list_curr].mainTexture = copyTexture;
        }

        // 外部テクスチャはコピーできない?
        if (false)
        {
            int texid = getTextureID4Unity();
            if (texid != -1)
            {
                IntPtr texidptr = new IntPtr(texid);
                Texture2D nativeTexture = Texture2D.CreateExternalTexture(
                    tex_sizeX, tex_sizeY,
                    TextureFormat.ARGB32,
                    false, false,
                    texidptr
                );

                IntPtr nativeData = nativeTexture.GetNativeTexturePtr();
                m_tex2d_2.UpdateExternalTexture(nativeData);

                {
                    var originalTexture = m_tex2d_2;
                    Texture2D copyTexture = new Texture2D(originalTexture.width, originalTexture.height, TextureFormat.ARGB32, false);
                    copyTexture.SetPixels32(originalTexture.GetPixels32());
                    copyTexture.Apply();
                    m_materials[name_list_curr].mainTexture = copyTexture;
                }

                //m_materials[name_list_curr].mainTexture = m_tex2d_2;
            }
        }
    }
0
0
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
0
0