Making a Texture2D readable in Unity via code

DavidGuaita picture DavidGuaita · Aug 7, 2014 · Viewed 29.3k times · Source

I have some AssetBundles that I want to convert to .png image files.

They are Texture2D assets, but the problem is as they are not Read Enable, when I try to convert them to PNG with a

var _bytes = _texture2d.EncodeToPNG();

command, I get the following error message:

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

I really can't access the Texture Import Settings, as they come from asset bundles and everything is made with code.

Somebody has a workaround for this?

Thanks

Answer

Ilya Suzdalnitski picture Ilya Suzdalnitski · Mar 10, 2015

Here's a working solution:

public static void SetTextureImporterFormat( Texture2D texture, bool isReadable)
{
    if ( null == texture ) return;

    string assetPath = AssetDatabase.GetAssetPath( texture );
    var tImporter = AssetImporter.GetAtPath( assetPath ) as TextureImporter;
    if ( tImporter != null )
    {
        tImporter.textureType = TextureImporterType.Advanced;

        tImporter.isReadable = isReadable;

        AssetDatabase.ImportAsset( assetPath );
        AssetDatabase.Refresh();
    }
}