Unity中Texture和Texture2D格式互相转换

在网络小游戏中有时候会有这样的需求的就是Texture和Texture2D类型的转换,例如:本地选择头像更换,背包图片的更新等.当然这方法只适用于小量级的小需求,大的需求会使用专门的处理类完成处理. 小游戏一般会使用更省性能的RawImage,不管怎么的使用场景,今天只分享技术.

其中的就是图片的动态转换了

( 编辑器模式下 )

///


/// 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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
(运行模式下)

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;
    }
--------------------- 
作者:月儿圆 
来源:CSDN 
原文:https://blog.csdn.net/s15100007883/article/details/80411638 
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(c#,Unity基础)