在网络小游戏中有时候会有这样的需求的就是Texture和Texture2D类型的转换,例如:本地选择头像更换,背包图片的更新等.当然这方法只适用于小量级的小需求,大的需求会使用专门的处理类完成处理. 小游戏一般会使用更省性能的RawImage,不管怎么的使用场景,今天只分享技术.
图片的动态转换
(编辑器模式下 )
/// <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;
}