问题描述
我正在使用 UnityWebRequestAssetBundle.GetAssetBundle(url,bundleData.version,bundleData.crc);
系统,我可以在线成功下载和使用 bundleAssets。但是当我想下载多个捆绑资产并将它们保存以供以后离线使用时,我遇到了问题。
我有 2 个文件,例如“A”和“B”。
案例1:当我下载A并离线时,即使我关闭应用程序,我也可以随时加载A。但是当我想下载 B 并返回 A 时无法再次加载 A,因为它出于某种原因删除了缓存并尝试再次下载。
案例 2:当我一起下载 A 和 B 并离线时,如果我加载 B,它会加载。但是如果我尝试 A 它无法加载并且需要互联网连接。之后,当我再次尝试加载 B 时,我丢失了包裹,因此它再次需要互联网连接。
所以基本上我想下载多个资产包,我想随时使用它们。我怎么解决这个问题?谢谢。
代码示例:
using UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(url,bundleData.crc);
yield return uwr.SendWebRequest();
bundle = DownloadHandlerAssetBundle.GetContent(uwr);
Debug.Log(bundle);
if (bundle==null)
{
Debug.Log("CouldN'T CONNECT TO URL");
callback(null);
}
else
{
Debug.Log("FOUND AT SEARCH!");
// Get downloaded asset bundle
bundle = DownloadHandlerAssetBundle.GetContent(uwr);
Sprite sprite = isDiff ? bundle.LoadAsset<Sprite>(levelText + "Diff") : bundle.LoadAsset<Sprite>(levelText);
callback(sprite);
}
解决方法
我通过将图像保存到persistentFolder 解决了我的问题。 我首先通过 Texture2D.EncodeToJPG() 将图像写入磁盘;
private void writeImageOnDisk(Sprite sprite,string fileName)
{
Texture2D texture = DeCompress(sprite.texture);
byte[] textureBytes = texture.EncodeToJPG();
File.WriteAllBytes(Application.persistentDataPath + "/" + fileName+".jpg",textureBytes);
Debug.Log("File Written On Disk!");
}
EncodeToJPG 图像必须在使用 AssetBundles 之前启用读/写,你应该先解压缩它们,我找到了解决方案 from this topic。
private Texture2D DeCompress(Texture2D source)
{
RenderTexture renderTex = RenderTexture.GetTemporary(
source.width,source.height,RenderTextureFormat.Default,RenderTextureReadWrite.Linear);
Graphics.Blit(source,renderTex);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = renderTex;
Texture2D readableText = new Texture2D(source.width,source.height);
readableText.ReadPixels(new Rect(0,renderTex.width,renderTex.height),0);
readableText.Apply();
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(renderTex);
return readableText;
}
最后,您可以使用此代码加载图像:
private Sprite loadImageFromDisk(string fileName)
{
string dataPath = Application.persistentDataPath + "/" + fileName + ".jpg";
if (!File.Exists(dataPath))
{
Debug.LogError("File Does Not Exist!");
return null;
}
byte[] textureBytes = File.ReadAllBytes(dataPath);
Texture2D loadedTexture = new Texture2D(2048,2048,TextureFormat.ARGB32,false);
loadedTexture.LoadImage(textureBytes);
Sprite spr = Sprite.Create(loadedTexture,new Rect(0f,0f,loadedTexture.width,loadedTexture.height),new Vector2(.5f,.5f),2048); // 2048 is pixel per unit if you have a custom pixelPerUnit value you should set it here. Or you will see only some part of pixels of image.
spr.name = fileName;
return spr;
}
我希望这对你们有用。这是我下载资源包后存储图像的方式以及我在游戏中调用它们的方式。