Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache images in unity android?

I want to cache images in unity for android platform. I use WWW to downloading images but it will download them again each time. I searched in unity documentation and web and found nothing useful. Any help will be appreciated.

like image 488
hojjat reyhane Avatar asked Sep 05 '25 03:09

hojjat reyhane


1 Answers

You could do one of two things

  1. Use Asset Bundles. Here's a link to building Asset Bundles in Unity 5.x. And here's an example

Asset bundles are an inbuilt feature, and it's really easy to integrate and use. Further, once any asset in downloaded with an AssetBundle, it's automatically cached as well (by default), and the next time, you won't need to re-download.

  1. The other option is to use a combination of WWW.bytes and File.WriteAllBytes (System.IO namespace) at Application.persistentDataPath.

This method is more convoluted, but if you don't have access to Asset Bundles (It's a Pro-only feature in 4.x) for any reason, this is one of the only ways to do it.

Partial example of Method #2

public class TestMyDownload : Monobehaviour {

    public string url = "http://www.example.com/bar.png";

    IEnumerator Start () {
        WWW www = new WWW(url);
        yield return www;

        if(www.bytes != null) {
            System.IO.File.WriteAllBytes(Application.persistentDataPath + "/myfile.png", www.bytes);
            Debug.Log("Writing Success");
        }
    }
}

EDIT : Just an FYI, method two can handle ALL types of data, not just images. If you're 100% sure you need only images, you can also access WWW.image

like image 198
Venkat at Axiom Studios Avatar answered Sep 07 '25 19:09

Venkat at Axiom Studios