ソースコード
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;
}
}
使用例
using System.IO;
using UnityEditor;
using UnityEngine;
public static class ExampleClass
{
[MenuItem( "Tools/Example" )]
private static void Example()
{
var type = typeof( GameObject );
var content = EditorGUIUtility.ObjectContent( null, type );
var image = content.image;
var tex = image.ToTexture2D();
var png = tex.EncodeToPNG();
File.WriteAllBytes( "result.png", png );
}
}
参考サイト様