Unity:Texture2D格式和RenderTexture、Texture格式的相互转换

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值