zrrz111

AssetBundleManager

Apr 8th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.19 KB | None | 0 0
  1. //------------------------------------------------------------------------------
  2. // <auto-generated>
  3. //     This code was generated by a tool.
  4. //     Runtime Version:4.0.30319.42000
  5. //
  6. //     Changes to this file may cause incorrect behavior and will be lost if
  7. //     the code is regenerated.
  8. // </auto-generated>
  9. //------------------------------------------------------------------------------
  10. using System;
  11. using UnityEngine;
  12. using System.Collections;
  13. using System.Collections.Generic;
  14.  
  15. public class AssetBundleManager : MonoBehaviour
  16. {
  17.  
  18.   public class CharacterBundle
  19.   {
  20.     public CharacterBundle(GameObject p_model, Texture2D p_icon, Texture2D p_sprite, bool p_isYoutubeCharacter)
  21.     {
  22.       model = p_model;
  23.       icon = p_icon;
  24.       sprite = p_sprite;
  25.       isYoutubeCharacter = p_isYoutubeCharacter;
  26.     }
  27.  
  28.     void MakeWarningsGoAway()
  29.     {
  30.       print(model.ToString() + icon.ToString() + sprite.ToString() + isYoutubeCharacter.ToString() + " ");
  31.     }
  32.  
  33.     public GameObject model;
  34.     public Texture2D icon;
  35.     public Texture2D sprite;
  36.     public bool isYoutubeCharacter;
  37.   }
  38.  
  39.   private class ABInfo
  40.   {
  41.         public ABInfo(string p_url, int p_version, int p_isYoutubeCharacter)
  42.     {
  43.       url = p_url;
  44.       version = p_version;
  45.       isYoutubeCharacter = p_isYoutubeCharacter;
  46.     }
  47.  
  48.     public string url;
  49.     public int version;
  50.     public int isYoutubeCharacter;
  51.   }
  52.  
  53.   enum DownloadState { NotStarted, Downloading, Done };
  54.  
  55.   /// <summary>
  56.   /// URL for asset list .txt document.
  57.   /// Format:
  58.   /// url version
  59.   /// www.url.url/filename.unity3d 4
  60.   /// </summary>
  61.   string remoteAssetListURL = "https://s3-us-west-1.amazonaws.com/deadrealm/files.txt";
  62.  
  63.   string localAssetListURL = "CharacterBundles/localCharacterBundles.txt";
  64.  
  65.   static DownloadState downloadState;
  66.  
  67.   List<CharacterBundle> characterBundles;
  68.  
  69.   [SerializeField]
  70.   bool downloadOnStart = true;
  71.  
  72.   public dfLabel downloadLabel;
  73.  
  74.   bool newestFilesDownloaded = false;
  75.  
  76.   static AssetBundleManager s_instance;
  77.   public static AssetBundleManager Instance
  78.   {
  79.     get
  80.     {
  81.       if (s_instance != null)
  82.       {
  83.         return s_instance;
  84.       }
  85.       else {
  86.         Debug.LogError("No AssetBundleManager in scene");
  87.         return null;
  88.       }
  89.     }
  90.   }
  91.  
  92.   void Awake()
  93.   {
  94.     DontDestroyOnLoad(gameObject);
  95.     s_instance = this;
  96.  
  97.     downloadLabel.gameObject.SetActive(false);
  98.  
  99.     Caching.CleanCache();
  100.  
  101.     if (downloadOnStart)
  102.     {
  103.       StartDownload();
  104.     }
  105.  
  106.   }
  107.  
  108.   void Update()
  109.   {
  110.     // Set to true if the current player downloaded all available characters
  111.     //GHGameManager.LobbyManager.SetCurrentLobbyCustCharDledState(downloadState == DownloadState.Done);
  112.   }
  113.  
  114.   /// <summary>
  115.   /// Gets the uninstatiated character bundles.
  116.   /// </summary>
  117.   /// <returns>The character bundles.</returns>
  118.   public static List<CharacterBundle> GetCharacterBundles()
  119.   {
  120.     return Instance.characterBundles;
  121.   }
  122.  
  123.   /// <summary>
  124.   /// Converts and returns instantiated character bundles into FBXImportData.
  125.   /// </summary>
  126.   /// <returns>The FBX import data.</returns>
  127.   public static List<GHFBXImportData> GetFBXImportData()
  128.   {
  129.     List<GHFBXImportData> importData = new List<GHFBXImportData>();
  130.  
  131.     if (Instance.characterBundles == null) { Debug.LogError("Charbundles are null"); }      
  132.  
  133.     List<CharacterBundle> characterBundles = Instance.characterBundles;
  134.     for (int i = 0; i < characterBundles.Count; i++)
  135.     {
  136.       GameObject character = (GameObject)Instantiate(characterBundles[i].model, Vector3.one * 9999f, Quaternion.identity);
  137.        
  138. //      foreach(Renderer rend in character.GetComponentsInChildren<Renderer>()) {
  139. //          Material[] mats = rend.sharedMaterials;  
  140. //          string[] shaders =  new string[mats.Length];
  141. //             
  142. //          for( int j = 0; j < mats.Length; j++)
  143. //          {
  144. //              shaders[j] = mats[j].shader.name;
  145. //          }          
  146. //         
  147. //          for( int j = 0; j < mats.Length; j++)
  148. //          {
  149. //              mats[j].shader = Shader.Find(shaders[j]);  
  150. //          }          
  151. //      }
  152.  
  153.         GHFBXImportData data = new GHFBXImportData();
  154.  
  155.       //Get Avatar
  156.       data.avatar = character.GetComponent<Animator>().avatar;
  157.       if (data.avatar == null)
  158.       {
  159.         Debug.LogError("Can't find Avatar");
  160.         return null;
  161.       }
  162.  
  163.       //Remove Animator
  164.       DestroyImmediate(character.GetComponent<Animator>());
  165.       if (data.avatar == null)
  166.       {
  167.         Debug.LogError("Avatar deleted");
  168.         return null;
  169.       }
  170.  
  171.       //Get Transforms
  172.       data.modelTransforms = character.GetComponentsInChildren<Transform>();
  173.  
  174.       // Get the name, icon, and sprite for character select screen
  175.       data.charName = character.gameObject.name.Replace("(Clone)", "");
  176.       data.gridCellIcon = characterBundles[i].icon;
  177.       data.hoverSprite = characterBundles[i].sprite;
  178.  
  179.       data.isYoutubeCharacter = characterBundles[i].isYoutubeCharacter;
  180.  
  181.       importData.Add(data);
  182.     }
  183.     return importData;
  184.   }
  185.     /// <summary>
  186.     /// Checks the current version of downloaded characters against the newest on the servers.
  187.     /// </summary>
  188.     /// <returns><c>true</c>, if download for newest was checked, <c>false</c> otherwise.</returns>
  189.     public static bool CheckDownloadForNewest() {
  190.         Instance.StartCoroutine(Instance.CheckDownloadForNewestInternal());
  191.         return Instance.newestFilesDownloaded;
  192.     }
  193.  
  194.     IEnumerator CheckDownloadForNewestInternal() {
  195.         newestFilesDownloaded = false;
  196.         using (WWW wwwFileList = new WWW(remoteAssetListURL))
  197.         {
  198.             yield return wwwFileList;
  199.             if(wwwFileList.error != null) {
  200.                 Debug.LogError("wwwFileList download had an error:" + wwwFileList.error);
  201.                 yield break;
  202.             }
  203.            
  204.             // Parse asset list into ABInfos - URL, Version
  205.             List<ABInfo> assetBundleInfos = new List<ABInfo>();
  206.             string[] assetBundlesURLs = wwwFileList.text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
  207.            
  208.             foreach (string url in assetBundlesURLs)
  209.             {
  210.                 string[] info = url.Split(new string[] { " ", "\t" }, StringSplitOptions.RemoveEmptyEntries);
  211.                 assetBundleInfos.Add(new ABInfo(info[0], int.Parse(info[1]), int.Parse(info[2])));
  212.             }
  213.            
  214.             // Wait for the Caching system to be ready
  215.             while (!Caching.ready)
  216.                 yield return null;
  217.            
  218.             foreach(ABInfo abInfo in assetBundleInfos) {
  219.                 if(!Caching.IsVersionCached(abInfo.url, abInfo.version)) {
  220.                     newestFilesDownloaded = false;
  221.                     yield break;
  222.                 }
  223.             }
  224.             newestFilesDownloaded = true;
  225.         }
  226.     }
  227.  
  228.   /// <summary>
  229.   /// Starts the download from assetListURL for character bundles.
  230.   /// </summary>
  231.   public static void StartDownload()
  232.   {
  233.     if (downloadState != DownloadState.Downloading)
  234.     {
  235.         if(Instance.downloadLabel != null) {
  236.             Instance.downloadLabel.gameObject.SetActive(true);
  237.             Instance.UpdateDownloadText(0);
  238.         }
  239.         Instance.StartCoroutine(Instance.RetryDownload());
  240.     }
  241.   }
  242.  
  243.     /// <summary>
  244.     /// Determines whether the character bundles are done downloading.
  245.     /// </summary>
  246.     /// <returns><c>true</c> if the download is done; otherwise, <c>false</c>.</returns>
  247.     public static bool IsDownloadDone()
  248.     {
  249.         return (downloadState == DownloadState.Done);
  250.     }
  251.  
  252.     IEnumerator RetryDownload() {
  253.         downloadState = DownloadState.Downloading;
  254.         while(downloadState == DownloadState.Downloading) {
  255.             yield return StartCoroutine(DownloadAndCache());
  256.             if(downloadState == DownloadState.Downloading) {
  257.                 Debug.LogError("Download failed. Trying again in 3 seconds.");
  258.                 yield return new WaitForSeconds(3f);
  259.             }
  260.         }
  261.         downloadLabel.gameObject.SetActive(false);
  262.     }
  263.  
  264.   IEnumerator DownloadAndCache()
  265.   {
  266.         {
  267.             //Local characters
  268.             List<ABInfo> assetBundleInfos = new List<ABInfo>();
  269.             TextAsset localAssetList = (TextAsset)Resources.Load (localAssetListURL, typeof(TextAsset));
  270.             if(localAssetList == null) {
  271.                 Debug.LogError("Can't find Resources/" + localAssetListURL, this);
  272.                 yield break;
  273.             }
  274.             string[] assetBundlesURLs = localAssetList.text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
  275.            
  276.             foreach (string url in assetBundlesURLs)
  277.             {
  278.                 string[] info = url.Split(new string[] { " ", "\t" }, StringSplitOptions.RemoveEmptyEntries);
  279.                 assetBundleInfos.Add(new ABInfo(info[0], int.Parse(info[1]), int.Parse (info[2])));
  280.             }
  281.            
  282.             // Wait for the Caching system to be ready
  283. //          while (!Caching.ready)
  284. //              yield return null;
  285.            
  286. //          int downloaded = -1;
  287.             // Load all character bundles from asset list
  288.             characterBundles = new List<CharacterBundle>();
  289.             foreach (ABInfo info in assetBundleInfos)
  290.             {
  291. ////                UpdateDownloadText((int)((float)downloaded/(float)assetBundleInfos.Count * 100f));
  292. ////                downloaded++;
  293. //
  294. //
  295. //              using (WWW www = WWW.LoadFromCacheOrDownload(info.url, info.version))
  296. //              {
  297. //                  yield return www;
  298. //                  if(www.error != null) {
  299. //                      Debug.LogError("WWW download had an error:" + www.error);
  300. //                      yield break;
  301. //                  }
  302. //                 
  303.                     AssetBundle bundle = Resources.Load(info.url) as AssetBundle;
  304. //                 
  305.                     //Parse asset bundle for character prefab
  306.                     GameObject model = (GameObject)bundle.LoadAll(typeof(GameObject))[0];
  307.                     Debug.Log(bundle.LoadAll(typeof(GameObject)).Length + " models in bundle");
  308.                    
  309.                     //Parse asset bundle for Icon and Sprite
  310.                     UnityEngine.Object[] images = bundle.LoadAll(typeof(Texture2D));
  311.                     Texture2D icon = null, sprite = null;
  312.                     for (int i = 0; i < images.Length; i++)
  313.                     {
  314.                         if (images[i].name.ToLower().Contains("icon"))
  315.                             icon = (Texture2D)images[i];
  316.                     }
  317.                     for (int i = 0; i < images.Length; i++)
  318.                     {
  319.                         if (images[i].name.ToLower().Contains("sprite") || images[i].name.ToLower().Contains("portrait"))
  320.                             sprite = (Texture2D)images[i];
  321.                     }
  322.                    
  323.                     characterBundles.Add(new CharacterBundle(model, icon, sprite, info.isYoutubeCharacter > 0));
  324.                     //          Debug.Log(
  325.                     //            characterBundles[characterBundles.Count - 1].model.name + "loaded with " +
  326.                     //            characterBundles[characterBundles.Count - 1].icon.name + "and " +
  327.                     //            characterBundles[characterBundles.Count - 1].sprite.name
  328.                     //            );
  329.                     // Unload the AssetBundles compressed contents to conserve memory
  330.                     //bundle.Unload(false); //TODO unload later
  331.                 }
  332. //          }
  333. //      }
  334.     }
  335.    
  336.     //Remote characters
  337.     using (WWW wwwFileList = new WWW(remoteAssetListURL))
  338.     {
  339.         //Download file list of character bundles
  340.         yield return wwwFileList;
  341.         if(wwwFileList.error != null) {
  342.             Debug.LogError("wwwFileList download had an error:" + wwwFileList.error);
  343.             yield break;
  344.         }
  345.      
  346.       // Parse asset list into ABInfos - URL, Version
  347.       List<ABInfo> assetBundleInfos = new List<ABInfo>();
  348.       string[] assetBundlesURLs = wwwFileList.text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
  349.  
  350.       foreach (string url in assetBundlesURLs)
  351.       {
  352.         string[] info = url.Split(new string[] { " ", "\t" }, StringSplitOptions.RemoveEmptyEntries);
  353.         assetBundleInfos.Add(new ABInfo(info[0], int.Parse(info[1]), int.Parse (info[2])));
  354.       }
  355.  
  356.       // Wait for the Caching system to be ready
  357.       while (!Caching.ready)
  358.         yield return null;
  359.  
  360.       int downloaded = -1;
  361.       // Load all character bundles from asset list
  362.       characterBundles = new List<CharacterBundle>();
  363.       foreach (ABInfo info in assetBundleInfos)
  364.       {
  365.         UpdateDownloadText((int)((float)downloaded/(float)assetBundleInfos.Count * 100f));
  366.         downloaded++;
  367.         using (WWW www = WWW.LoadFromCacheOrDownload(info.url, info.version))
  368.         {
  369.           yield return www;
  370.           if(www.error != null) {
  371.             Debug.LogError("WWW download had an error:" + www.error);
  372.             yield break;
  373.           }
  374.  
  375.           AssetBundle bundle = www.assetBundle;
  376.  
  377.           //Parse asset bundle for character prefab
  378.           GameObject model = (GameObject)bundle.LoadAll(typeof(GameObject))[0];
  379.           Debug.Log(bundle.LoadAll(typeof(GameObject)).Length + " models in bundle");
  380.  
  381.           //Parse asset bundle for Icon and Sprite
  382.           UnityEngine.Object[] images = bundle.LoadAll(typeof(Texture2D));
  383.           Texture2D icon = null, sprite = null;
  384.           for (int i = 0; i < images.Length; i++)
  385.           {
  386.             if (images[i].name.ToLower().Contains("icon"))
  387.               icon = (Texture2D)images[i];
  388.           }
  389.           for (int i = 0; i < images.Length; i++)
  390.           {
  391.             if (images[i].name.ToLower().Contains("sprite") || images[i].name.ToLower().Contains("portrait"))
  392.               sprite = (Texture2D)images[i];
  393.           }
  394.  
  395.           characterBundles.Add(new CharacterBundle(model, icon, sprite, info.isYoutubeCharacter > 0));
  396. //          Debug.Log(
  397. //            characterBundles[characterBundles.Count - 1].model.name + "loaded with " +
  398. //            characterBundles[characterBundles.Count - 1].icon.name + "and " +
  399. //            characterBundles[characterBundles.Count - 1].sprite.name
  400. //            );
  401.           // Unload the AssetBundles compressed contents to conserve memory
  402.           //bundle.Unload(false); //TODO unload later
  403.         }
  404.       }
  405.     }
  406.  
  407.     string loaded = characterBundles.Count + " characters loaded: ";
  408.     for (int i = 0; i < characterBundles.Count; i++)
  409.     {
  410.       loaded += characterBundles[i].model.name + (i == characterBundles.Count - 1 ? "" : ", ");
  411.     }
  412.     Debug.Log(loaded, this);
  413.  
  414.     downloadState = DownloadState.Done;
  415.  
  416.     // Set to true if the current player downloaded all available characters
  417.     GHGameManager.LobbyManager.SetCurrentLobbyCustCharDledState(downloadState == DownloadState.Done);
  418.   }
  419.  
  420.     void UpdateDownloadText(int percentage) {
  421.         downloadLabel.Text = "Downloading new Characters: " + percentage + "%";
  422.     }
  423. }
Advertisement
Add Comment
Please, Sign In to add comment