RenderTexture和Texture2D是继承于Texture类的,它们之间彼此可以进行相互的转换,但不能强转。之前我在做项目的时候就进行强转,强转在代码里是不会报错的,但是运行的时候不能真正转换成功,从而导致没有效果。
下面总结它们彼此相互转换的方法:
/// <summary>
/// 编辑器模式下Texture转换成Texture2D
/// </summary>
/// <param name="texture"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 运行模式下Texture转换成Texture2D
/// </summary>
/// <param name="texture"></param>
/// <returns></returns>
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;
}
int width = renderTexture.width;
int height = renderTexture.height;
Texture2D texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false);
RenderTexture.active = renderTexture;
texture2D.ReadPixels(new Rect(0, 0, width, height), 0, 0);
texture2D.Apply();
参考博文:https://blog.csdn.net/s15100007883/article/details/80411638
https://blog.csdn.net/alayeshi/article/details/52576747