Guest User

Untitled

a guest
Jun 24th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.66 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.IO;
  4.  
  5. public class TextureWWWCacher : MonoBehaviour {
  6.    
  7.    
  8.     WWW web;
  9.     public string imgUrl;
  10.     public string cacheFile = "superbanner.png";
  11.      public Texture2D resultTexture;
  12.    
  13.     string bannerCache_key = "nt_current_banner_cache";
  14.    
  15.     string imageFile = "";
  16.     // Use this for initialization
  17.     public IEnumerator fetch () {
  18.    
  19.         yield return fetch(imgUrl,-1,-1);
  20.        
  21.     }
  22.    
  23.    
  24.     //this one uses bannerName instead of url to see if we have cached it
  25.     public  IEnumerator fetch (string bannerName,int resX,int resY) {
  26.    
  27.        
  28.         imageFile = Application.persistentDataPath  + "/supperbanner.png";
  29.         resultTexture = new Texture2D(0,0);
  30.        
  31.        
  32.         string hasCachedKey = PlayerPrefs.GetString(bannerCache_key,"");
  33.         if( bannerName != hasCachedKey ){
  34.        
  35.             Debug.Log("downloading image file " + imgUrl);
  36.             //we should download this new version..
  37.            
  38.             WWW web = new WWW(imgUrl);
  39.             yield return web;
  40.        
  41.             if(web.error == null)
  42.             {
  43.                 /*if(resX>0){
  44.                     web.texture.Resize(resX,resY);
  45.                     web.texture.Apply();
  46.                 }*/
  47.                 byte[] image = web.texture.EncodeToPNG();
  48.                 File.WriteAllBytes(imageFile, image);
  49.                 PlayerPrefs.SetString(bannerCache_key,bannerName);
  50.             }
  51.             else{
  52.                 Debug.Log("error downloading image file:" + web.error);
  53.                     resultTexture = null;
  54.                    
  55.             }
  56.         }
  57.         else{
  58.             Debug.Log("loading directly from cache");
  59.         }
  60.        
  61.         if(resultTexture!= null){
  62.             byte[] loadedImage = File.ReadAllBytes(imageFile);
  63.             resultTexture.LoadImage(loadedImage);
  64.             /*resultTexture.Resize(512,256);
  65.             resultTexture.Apply();//*/
  66.         }
  67.     }
  68.    
  69.     // Update is called once per frame
  70.     void Update () {
  71.        
  72.     }
  73. }
Add Comment
Please, Sign In to add comment