Unity Texture转Texture2D

图片的动态转换

分为两种模式:
编辑器时,可以直接as后,然后保存;
运行时,需要拿RenderTexture来进行一次像素的转化

(编辑器模式下 )

/// 编辑器模式下Texture转换成Texture2D
private Texture2D TextureToTexture2D(Texture texture) 
{
	    Texture2D texture2d = texture as Texture2D;
	    UnityEditor.TextureImporter ti = (UnityEditor.TextureImporter)UnityEditor.TextureImporter.GetAtPath(UnityEditor.AssetDatabase.GetAssetPath(texture2d));
	    //图片Read/Write Enable的开关
	    ti.isReadable = true; 
	    UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(texture2d));
	    return texture2d;
}

(运行模式下)

/// 运行模式下Texture转换成Texture2D
private Texture2D TextureToTexture2D(Texture texture) 
{
        Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
        RenderTexture currentRT = RenderTexture.active;
        RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
        Graphics.Blit(texture, renderTexture);

        RenderTexture.active = renderTexture;
        texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture2D.Apply();

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

        return texture2D;
}

你可能感兴趣的:(Unity)