DLC - Help downloading assets and saving locally
Hi All,
I'm currently working on a game that is server oriented. The game downloads it save file from the server as well as telling the server about each action.
The next part of the game is to be able to download new assets e.g. New player texture.
I currently have my textures in the Resource folder and I use Resource.Load() to load them at runtime.
Is there anyway to download a new image and save it in the resource folder?
Also is it possible to download the new image, and have it stored locally, so next time the game is loaded it won't need downloading again?
Thanks Thomas
Answer by rmail2006 · Jun 01, 2017 at 10:44 PM
I figured out a better way to do this.
I couldn't get an image into the resources so I figured another way around it.
First thing I do is check if the image exists in the Resources folder, if that doesn't exist i then use File.exists to check if the image is in the persistantDataPath subdirectory, if not then use a WWW to download it from my server, and then File.WriteAllBytes to write it to the persistantDataPath.
So from now on, when the game loads it will look in the persistantDataPath and it will load it without checking my server.
It works for what I need and after testing multiple times, the game loads at similar times with the image in the resource folder compared to downloading it from the server.
EXAMPLE
jn is a json node
m.image = Resources.Load<Sprite>("Sprites/" + Path.GetFileNameWithoutExtension(jn["IMG"]));
if (m.image == null)
{
if (!File.Exists(Application.persistentDataPath + "/Sprites/" + jn["IMG"]))
{
string imageURL = "http://localhost/game/Sprites/";
www = new WWW(imageURL + jn["IMG"]);
yield return www;
byte[] bytes = www.texture.EncodeToPNG();
File.WriteAllBytes(Application.persistentDataPath + "/Sprites/" + jn["IMG"], bytes);
Debug.Log("Downloaded Sprite");
}
byte[] data = File.ReadAllBytes(Application.persistentDataPath + "/Sprites/" + jn["IMG"]);
Texture2D tex = new Texture2D(450, 500, TextureFormat.ARGB32, false);
tex.LoadImage(data);
Sprite s = Sprite.Create(tex, new Rect(0, 0, 450, 500), new Vector2(0, 0));
m.image = s;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612123125im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Needed objects destroyed after deserialization 0 Answers
How to make an exetuable file lighter 1 Answer
Loading Assets from server on as needed basis. 0 Answers
Warning:Trying to move asset to location it came from...[Please Help] 0 Answers
How do you import non-hierarcy assets from an Asset Bundle? 1 Answer