Unity5.3资源热更新

转载自:http://blog.csdn.net/l_jinxiong/article/details/50877926

Unity5以下的版本,要导出AssetBundle需要自己写一大坨导出的代码(BuildPipeline),想正确处理好资源的依赖关系从而保证资源完整而又不会产生重复资源是一件非常困难的事。Unity5新的AssetBundle系统大大简化了这一操作。Unity打包的时候会自动处理依赖关系,并生成一个.manifest文件,这个文件描述了assetbundle包大小、crc验证、包之间的依赖关系等等,是一个文本文件(但是这个也有坑,有时候prefab更新,重新打包却没有生成新的AssetBundle)。

打包Assetbundle的代码如下

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public static void BuildAssetResource(BuildTarget target)  
  2. {  
  3.     string dataPath = Util.DataPath;  
  4.     if (Directory.Exists(dataPath))  
  5.     {  
  6.         Directory.Delete(dataPath, true);  
  7.     }  
  8.     string resPath = Util.AppDataPath + "/" + AppConst.AssetDirname + "/";  
  9.     if (!Directory.Exists(resPath))  
  10.     {  
  11.         Directory.CreateDirectory(resPath);  
  12.     }  
  13.   
  14.     //生成assetbundle  
  15.     BuildPipeline.BuildAssetBundles(resPath, BuildAssetBundleOptions.None, target);  
  16.   
  17.     paths.Clear();   
  18.     files.Clear();  
  19.     EditorUtility.ClearProgressBar();  
  20.   
  21.     ///----------------------创建文件列表-----------------------  
  22.     string newFilePath = resPath + "/files.txt";  
  23.     if (File.Exists(newFilePath)) File.Delete(newFilePath);  
  24.   
  25.     paths.Clear();   
  26.     files.Clear();  
  27.     Recursive(resPath);  
  28.   
  29.     FileStream fs = new FileStream(newFilePath, FileMode.CreateNew);  
  30.     StreamWriter sw = new StreamWriter(fs);  
  31.     for (int i = 0; i < files.Count; i++)  
  32.     {  
  33.         string file = files[i];  
  34.         if (file.EndsWith(".meta") || file.Contains(".DS_Store"))  
  35.         {  
  36.             continue;  
  37.         }  
  38.   
  39.         string md5 = Util.md5file(file);  
  40.         string value = file.Replace(resPath, string.Empty);  
  41.         sw.WriteLine(value + "|" + md5);  
  42.     }  
  43.     sw.Close();   
  44.     fs.Close();  
  45.     AssetDatabase.Refresh();  
  46. }  

在资源属性窗口底部有一个选项,设置AssetBundle的名字,设置好AssetBundle的名字调用上面的函数就可以把全部的Assetbundle生成出来。AssetBundle的名字固定为小写。另外,每个AssetBundle都可以设置一个Variant,其实就是一个后缀,实际AssetBundle的名字会添加这个后缀。如果有不同分辨率的同名资源,可以使用这个来做区分。



加载Assetbundle的代码

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. namespace AssetBundles  
  5. {  
  6.     public abstract class AssetBundleLoadOperation : IEnumerator  
  7.     {  
  8.         public object Current  
  9.         {  
  10.             get  
  11.             {  
  12.                 return null;  
  13.             }  
  14.         }  
  15.         public bool MoveNext()  
  16.         {  
  17.             return !IsDone();  
  18.         }  
  19.   
  20.         public void Reset()  
  21.         {  
  22.         }  
  23.   
  24.         abstract public bool Update();  
  25.   
  26.         abstract public bool IsDone();  
  27.     }  
  28.   
  29.     public class AssetBundleLoadLevelOperation : AssetBundleLoadOperation  
  30.     {  
  31.         protected string m_AssetBundleName;  
  32.         protected string m_LevelName;  
  33.         protected bool m_IsAdditive;  
  34.         protected string m_DownloadingError;  
  35.         protected AsyncOperation m_Request;  
  36.   
  37.         public AssetBundleLoadLevelOperation(string assetbundleName, string levelName, bool isAdditive)  
  38.         {  
  39.             m_AssetBundleName = assetbundleName;  
  40.             m_LevelName = levelName;  
  41.             m_IsAdditive = isAdditive;  
  42.         }  
  43.   
  44.         public override bool Update()  
  45.         {  
  46.             if (m_Request != null)  
  47.                 return false;  
  48.   
  49.             LoadedAssetBundle bundle = AssetBundleManager.GetLoadedAssetBundle(m_AssetBundleName, out m_DownloadingError);  
  50.             if (bundle != null)  
  51.             {  
  52.                 if (m_IsAdditive)  
  53.                     m_Request = Application.LoadLevelAdditiveAsync(m_LevelName);  
  54.                 else  
  55.                     m_Request = Application.LoadLevelAsync(m_LevelName);  
  56.                 return false;  
  57.             }  
  58.             else  
  59.                 return true;  
  60.         }  
  61.   
  62.         public override bool IsDone()  
  63.         {  
  64.             if (m_Request == null && m_DownloadingError != null)  
  65.             {  
  66.                 Debug.LogError(m_DownloadingError);  
  67.                 return true;  
  68.             }  
  69.   
  70.             return m_Request != null && m_Request.isDone;  
  71.         }  
  72.     }  
  73.   
  74.     public abstract class AssetBundleLoadAssetOperation : AssetBundleLoadOperation  
  75.     {  
  76.         public abstract T GetAsset<T>() where T : UnityEngine.Object;  
  77.     }  
  78.   
  79.     public class AssetBundleLoadAssetOperationSimulation : AssetBundleLoadAssetOperation  
  80.     {  
  81.         Object m_SimulatedObject;  
  82.   
  83.         public AssetBundleLoadAssetOperationSimulation(Object simulatedObject)  
  84.         {  
  85.             m_SimulatedObject = simulatedObject;  
  86.         }  
  87.   
  88.         public override T GetAsset<T>()  
  89.         {  
  90.             return m_SimulatedObject as T;  
  91.         }  
  92.   
  93.         public override bool Update()  
  94.         {  
  95.             return false;  
  96.         }  
  97.   
  98.         public override bool IsDone()  
  99.         {  
  100.             return true;  
  101.         }  
  102.     }  
  103.   
  104.     public class AssetBundleLoadAssetOperationFull : AssetBundleLoadAssetOperation  
  105.     {  
  106.         protected string m_AssetBundleName;  
  107.         protected string m_AssetName;  
  108.         protected string m_DownloadingError;  
  109.         protected System.Type m_Type;  
  110.         protected AssetBundleRequest m_Request = null;  
  111.   
  112.         public AssetBundleLoadAssetOperationFull(string bundleName, string assetName, System.Type type)  
  113.         {  
  114.             m_AssetBundleName = bundleName;  
  115.             m_AssetName = assetName;  
  116.             m_Type = type;  
  117.         }  
  118.   
  119.         public override T GetAsset<T>()  
  120.         {  
  121.             if (m_Request != null && m_Request.isDone)  
  122.             {  
  123.                 return m_Request.asset as T;  
  124.             }  
  125.             else  
  126.             {  
  127.                 return null;  
  128.             }  
  129.         }  
  130.   
  131.         public override bool Update()  
  132.         {  
  133.             if (m_Request != null)  
  134.                 return false;  
  135.   
  136.             LoadedAssetBundle bundle = AssetBundleManager.GetLoadedAssetBundle(m_AssetBundleName, out m_DownloadingError);  
  137.             if (bundle != null)  
  138.             {  
  139.                 m_Request = bundle.m_AssetBundle.LoadAssetAsync(m_AssetName, m_Type);  
  140.                 return false;  
  141.             }  
  142.             else  
  143.             {  
  144.                 return true;  
  145.             }  
  146.         }  
  147.   
  148.         public override bool IsDone()  
  149.         {  
  150.             if (m_Request == null && m_DownloadingError != null)  
  151.             {  
  152.                 Debug.LogError(m_DownloadingError);  
  153.                 return true;  
  154.             }  
  155.   
  156.             return m_Request != null && m_Request.isDone;  
  157.         }  
  158.     }  
  159.   
  160.     public class AssetBundleLoadManifestOperation : AssetBundleLoadAssetOperationFull  
  161.     {  
  162.         public AssetBundleLoadManifestOperation(string bundleName, string assetName, System.Type type)  
  163.             : base(bundleName, assetName, type)  
  164.         {  
  165.         }  
  166.   
  167.         public override bool Update()  
  168.         {  
  169.             base.Update();  
  170.   
  171.             if (m_Request != null && m_Request.isDone)  
  172.             {  
  173.                 AssetBundleManager.AssetBundleManifestObject = GetAsset<AssetBundleManifest>();  
  174.                 return false;  
  175.             }  
  176.             else  
  177.             {  
  178.                 return true;  
  179.             }  
  180.         }  
  181.     }  
  182. }  

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. using UnityEngine;  
  2. #if UNITY_EDITOR  
  3. using UnityEditor;  
  4. #endif  
  5. using System.Collections;  
  6. using System.Collections.Generic;  
  7. namespace AssetBundles  
  8. {  
  9.     public class LoadedAssetBundle  
  10.     {  
  11.         public AssetBundle m_AssetBundle;  
  12.         public int m_ReferencedCount;  
  13.   
  14.         public LoadedAssetBundle(AssetBundle assetBundle)  
  15.         {  
  16.             m_AssetBundle = assetBundle;  
  17.             m_ReferencedCount = 1;  
  18.         }  
  19.     }  
  20.   
  21.     public class AssetBundleManager : MonoBehaviour  
  22.     {  
  23.         static string m_BaseDownloadingURL = "";  
  24.         static string[] m_ActiveVariants = { };  
  25.         static AssetBundleManifest m_AssetBundleManifest = null;  
  26.         static Dictionary<string, LoadedAssetBundle> m_LoadedAssetBundles = new Dictionary<string, LoadedAssetBundle>();  
  27.         static Dictionary<string, WWW> m_DownloadingWWWs = new Dictionary<string, WWW>();  
  28.         static Dictionary<stringstring> m_DownloadingErrors = new Dictionary<stringstring>();  
  29.         static List<AssetBundleLoadOperation> m_InProgressOperations = new List<AssetBundleLoadOperation>();  
  30.         static Dictionary<stringstring[]> m_Dependencies = new Dictionary<stringstring[]>();  
  31.   
  32.         // The base downloading url which is used to generate the full downloading url with the assetBundle names.  
  33.         public static string BaseDownloadingURL  
  34.         {  
  35.             get { return m_BaseDownloadingURL; }  
  36.             set { m_BaseDownloadingURL = value; }  
  37.         }  
  38.   
  39.         // Variants which is used to define the active variants.  
  40.         public static string[] ActiveVariants  
  41.         {  
  42.             get { return m_ActiveVariants; }  
  43.             set { m_ActiveVariants = value; }  
  44.         }  
  45.   
  46.         // AssetBundleManifest object which can be used to load the dependecies and check suitable assetBundle variants.  
  47.         public static AssetBundleManifest AssetBundleManifestObject  
  48.         {  
  49.             set { m_AssetBundleManifest = value; }  
  50.         }  
  51.   
  52.         public static void SetSourceAssetBundleDirectory(string relativePath)  
  53.         {  
  54.             BaseDownloadingURL = Util.GetStreamingAssetsPath() + relativePath;  
  55.         }  
  56.   
  57.         public static void SetSourceAssetBundleURL(string absolutePath)  
  58.         {  
  59.             BaseDownloadingURL = absolutePath + Utility.GetPlatformName() + "/";  
  60.         }  
  61.   
  62.         public static void SetDevelopmentAssetBundleServer()  
  63.         {  
  64.             TextAsset urlFile = Resources.Load("AssetBundleServerURL"as TextAsset;  
  65.             string url = (urlFile != null) ? urlFile.text.Trim() : null;  
  66.             if (url == null || url.Length == 0)  
  67.             {  
  68.                 Debug.LogError("Development Server URL could not be found.");  
  69.             }  
  70.             else  
  71.             {  
  72.                 AssetBundleManager.SetSourceAssetBundleURL(url);  
  73.             }  
  74.         }  
  75.   
  76.         // Get loaded AssetBundle, only return vaild object when all the dependencies are downloaded successfully.  
  77.         static public LoadedAssetBundle GetLoadedAssetBundle(string assetBundleName, out string error)  
  78.         {  
  79.             if (m_DownloadingErrors.TryGetValue(assetBundleName, out error))  
  80.             {  
  81.                 return null;  
  82.             }  
  83.   
  84.             LoadedAssetBundle bundle = null;  
  85.             m_LoadedAssetBundles.TryGetValue(assetBundleName, out bundle);  
  86.             if (bundle == null)  
  87.             {  
  88.                 return null;  
  89.             }  
  90.   
  91.             // No dependencies are recorded, only the bundle itself is required.  
  92.             string[] dependencies = null;  
  93.             if (!m_Dependencies.TryGetValue(assetBundleName, out dependencies))  
  94.             {  
  95.                 return bundle;  
  96.             }  
  97.   
  98.             // Make sure all dependencies are loaded  
  99.             foreach (var dependency in dependencies)  
  100.             {  
  101.                 if (m_DownloadingErrors.TryGetValue(assetBundleName, out error))  
  102.                 {  
  103.                     return bundle;  
  104.                 }  
  105.   
  106.                 // Wait all the dependent assetBundles being loaded.  
  107.                 LoadedAssetBundle dependentBundle;  
  108.                 m_LoadedAssetBundles.TryGetValue(dependency, out dependentBundle);  
  109.                 if (dependentBundle == null)  
  110.                 {  
  111.                     return null;  
  112.                 }  
  113.             }  
  114.   
  115.             return bundle;  
  116.         }  
  117.   
  118.         public static AssetBundleLoadManifestOperation Initialize()  
  119.         {  
  120.             BaseDownloadingURL = Util.GetRelativePath();  
  121. //            return Initialize(Utility.GetPlatformName());  
  122.             return Initialize(AppConst.AssetDirname);  
  123.         }  
  124.   
  125.         // Load AssetBundleManifest.  
  126.         public static AssetBundleLoadManifestOperation Initialize(string manifestAssetBundleName)  
  127.         {  
  128.             var go = new GameObject("AssetBundleManager"typeof(AssetBundleManager));  
  129.             DontDestroyOnLoad(go);  
  130.             LoadAssetBundle(manifestAssetBundleName, true);  
  131.             var operation = new AssetBundleLoadManifestOperation(manifestAssetBundleName, "AssetBundleManifest"typeof(AssetBundleManifest));  
  132.             m_InProgressOperations.Add(operation);  
  133.             return operation;  
  134.         }  
  135.   
  136.         // Load AssetBundle and its dependencies.  
  137.         protected static void LoadAssetBundle(string assetBundleName, bool isLoadingAssetBundleManifest = false)  
  138.         {  
  139.             if (!isLoadingAssetBundleManifest)  
  140.             {  
  141.                 if (m_AssetBundleManifest == null)  
  142.                 {  
  143.                     Debug.LogError("Please initialize AssetBundleManifest by calling AssetBundleManager.Initialize()");  
  144.                     return;  
  145.                 }  
  146.             }  
  147.   
  148.             // Check if the assetBundle has already been processed.  
  149.             bool isAlreadyProcessed = LoadAssetBundleInternal(assetBundleName, isLoadingAssetBundleManifest);  
  150.   
  151.             // Load dependencies.  
  152.             if (!isAlreadyProcessed && !isLoadingAssetBundleManifest)  
  153.             {  
  154.                 LoadDependencies(assetBundleName);  
  155.             }  
  156.         }  
  157.   
  158.         // Remaps the asset bundle name to the best fitting asset bundle variant.  
  159.         protected static string RemapVariantName(string assetBundleName)  
  160.         {  
  161.             string[] bundlesWithVariant = m_AssetBundleManifest.GetAllAssetBundlesWithVariant();  
  162.   
  163.             string[] split = assetBundleName.Split('.');  
  164.   
  165.             int bestFit = int.MaxValue;  
  166.             int bestFitIndex = -1;  
  167.             // Loop all the assetBundles with variant to find the best fit variant assetBundle.  
  168.             for (int i = 0; i < bundlesWithVariant.Length; i++)  
  169.             {  
  170.                 string[] curSplit = bundlesWithVariant[i].Split('.');  
  171.                 if (curSplit[0] != split[0])  
  172.                     continue;  
  173.   
  174.                 int found = System.Array.IndexOf(m_ActiveVariants, curSplit[1]);  
  175.   
  176.                 // If there is no active variant found. We still want to use the first   
  177.                 if (found == -1)  
  178.                     found = int.MaxValue - 1;  
  179.   
  180.                 if (found < bestFit)  
  181.                 {  
  182.                     bestFit = found;  
  183.                     bestFitIndex = i;  
  184.                 }  
  185.             }  
  186.   
  187.             if (bestFit == int.MaxValue - 1)  
  188.             {  
  189.                 Debug.LogWarning("Ambigious asset bundle variant chosen because there was no matching active variant: " + bundlesWithVariant[bestFitIndex]);  
  190.             }  
  191.   
  192.             if (bestFitIndex != -1)  
  193.             {  
  194.                 return bundlesWithVariant[bestFitIndex];  
  195.             }  
  196.             else  
  197.             {  
  198.                 return assetBundleName;  
  199.             }  
  200.         }  
  201.   
  202.         // Where we actuall call WWW to download the assetBundle.  
  203.         protected static bool LoadAssetBundleInternal(string assetBundleName, bool isLoadingAssetBundleManifest)  
  204.         {  
  205.             // Already loaded.  
  206.             LoadedAssetBundle bundle = null;  
  207.             m_LoadedAssetBundles.TryGetValue(assetBundleName, out bundle);  
  208.             if (bundle != null)  
  209.             {  
  210.                 bundle.m_ReferencedCount++;  
  211.                 return true;  
  212.             }  
  213.             if (m_DownloadingWWWs.ContainsKey(assetBundleName))  
  214.             {  
  215.                 return true;  
  216.             }  
  217.   
  218.             WWW download = null;  
  219.             string url = m_BaseDownloadingURL + assetBundleName;  
  220.   
  221.             // For manifest assetbundle, always download it as we don't have hash for it.  
  222.             if (isLoadingAssetBundleManifest)  
  223.             {  
  224.                 download = new WWW(url);  
  225.             }  
  226.             else  
  227.             {  
  228.                 download = WWW.LoadFromCacheOrDownload(url, m_AssetBundleManifest.GetAssetBundleHash(assetBundleName), 0);  
  229.             }  
  230.   
  231.             m_DownloadingWWWs.Add(assetBundleName, download);  
  232.   
  233.             return false;  
  234.         }  
  235.   
  236.         // Where we get all the dependencies and load them all.  
  237.         static protected void LoadDependencies(string assetBundleName)  
  238.         {  
  239.             if (m_AssetBundleManifest == null)  
  240.             {  
  241.                 Debug.LogError("Please initialize AssetBundleManifest by calling AssetBundleManager.Initialize()");  
  242.                 return;  
  243.             }  
  244.   
  245.             // Get dependecies from the AssetBundleManifest object..  
  246.             string[] dependencies = m_AssetBundleManifest.GetAllDependencies(assetBundleName);  
  247.             if (dependencies.Length == 0)  
  248.                 return;  
  249.   
  250.             for (int i = 0; i < dependencies.Length; i++)  
  251.             {  
  252.                 dependencies[i] = RemapVariantName(dependencies[i]);  
  253.             }  
  254.   
  255.             // Record and load all dependencies.  
  256.             m_Dependencies.Add(assetBundleName, dependencies);  
  257.             for (int i = 0; i < dependencies.Length; i++)  
  258.             {  
  259.                 LoadAssetBundleInternal(dependencies[i], false);  
  260.             }  
  261.         }  
  262.   
  263.         // Unload assetbundle and its dependencies.  
  264.         static public void UnloadAssetBundle(string assetBundleName)  
  265.         {  
  266.             UnloadAssetBundleInternal(assetBundleName);  
  267.             UnloadDependencies(assetBundleName);  
  268.         }  
  269.   
  270.         static protected void UnloadDependencies(string assetBundleName)  
  271.         {  
  272.             string[] dependencies = null;  
  273.             if (!m_Dependencies.TryGetValue(assetBundleName, out dependencies))  
  274.             {  
  275.                 return;  
  276.             }  
  277.   
  278.             // Loop dependencies.  
  279.             foreach (var dependency in dependencies)  
  280.             {  
  281.                 UnloadAssetBundleInternal(dependency);  
  282.             }  
  283.   
  284.             m_Dependencies.Remove(assetBundleName);  
  285.         }  
  286.   
  287.         static protected void UnloadAssetBundleInternal(string assetBundleName)  
  288.         {  
  289.             string error;  
  290.             LoadedAssetBundle bundle = GetLoadedAssetBundle(assetBundleName, out error);  
  291.             if (bundle == null)  
  292.             {  
  293.                 return;  
  294.             }  
  295.   
  296.             if (--bundle.m_ReferencedCount == 0)  
  297.             {  
  298.                 bundle.m_AssetBundle.Unload(false);  
  299.                 m_LoadedAssetBundles.Remove(assetBundleName);  
  300.             }  
  301.         }  
  302.   
  303.         void Update()  
  304.         {  
  305.             // Collect all the finished WWWs.  
  306.             var keysToRemove = new List<string>();  
  307.             foreach (var keyValue in m_DownloadingWWWs)  
  308.             {  
  309.                 WWW download = keyValue.Value;  
  310.   
  311.                 // If downloading fails.  
  312.                 if (download.error != null)  
  313.                 {  
  314.                     m_DownloadingErrors.Add(keyValue.Key, string.Format("Failed downloading bundle {0} from {1}: {2}", keyValue.Key, download.url, download.error));  
  315.                     keysToRemove.Add(keyValue.Key);  
  316.                     continue;  
  317.                 }  
  318.   
  319.                 // If downloading succeeds.  
  320.                 if (download.isDone)  
  321.                 {  
  322.                     AssetBundle bundle = download.assetBundle;  
  323.                     if (bundle == null)  
  324.                     {  
  325.                         m_DownloadingErrors.Add(keyValue.Key, string.Format("{0} is not a valid asset bundle.", keyValue.Key));  
  326.                         keysToRemove.Add(keyValue.Key);  
  327.                         continue;  
  328.                     }  
  329.                     m_LoadedAssetBundles.Add(keyValue.Key, new LoadedAssetBundle(download.assetBundle));  
  330.                     keysToRemove.Add(keyValue.Key);  
  331.                 }  
  332.             }  
  333.   
  334.             // Remove the finished WWWs.  
  335.             foreach (var key in keysToRemove)  
  336.             {  
  337.                 WWW download = m_DownloadingWWWs[key];  
  338.                 m_DownloadingWWWs.Remove(key);  
  339.                 download.Dispose();  
  340.             }  
  341.   
  342.             // Update all in progress operations  
  343.             for (int i = 0; i < m_InProgressOperations.Count; )  
  344.             {  
  345.                 if (!m_InProgressOperations[i].Update())  
  346.                 {  
  347.                     m_InProgressOperations.RemoveAt(i);  
  348.                 }  
  349.                 else  
  350.                 {  
  351.                     i++;  
  352.                 }  
  353.             }  
  354.         }  
  355.   
  356.         // Load asset from the given assetBundle.  
  357.         public static AssetBundleLoadAssetOperation LoadAssetAsync(string assetBundleName, string assetName, System.Type type)  
  358.         {  
  359.             AssetBundleLoadAssetOperation operation = null;  
  360.             assetBundleName = RemapVariantName(assetBundleName);  
  361.             LoadAssetBundle(assetBundleName);  
  362.             operation = new AssetBundleLoadAssetOperationFull(assetBundleName, assetName, type);  
  363.             m_InProgressOperations.Add(operation);             
  364.             return operation;  
  365.         }  
  366.   
  367.         // Load level from the given assetBundle.  
  368.         public static AssetBundleLoadOperation LoadLevelAsync(string assetBundleName, string levelName, bool isAdditive)  
  369.         {  
  370.             AssetBundleLoadOperation operation = null;  
  371.             assetBundleName = RemapVariantName(assetBundleName);  
  372.             LoadAssetBundle(assetBundleName);  
  373.             operation = new AssetBundleLoadLevelOperation(assetBundleName, levelName, isAdditive);  
  374.             m_InProgressOperations.Add(operation);  
  375.             return operation;  
  376.         }  
  377.     }   
  378. }  

客户端更新Assetbundle的时候并不是把全部生成的Assetbundle都下载更新,前面打包Assetbundle的时候生成一个一个files.txt的文件,这个文件里记录了每个Assetbundle的md5值,只有md5值变了的才会下载

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. IEnumerator OnUpdateResource()  
  2. {  
  3.     string dataPath = Util.DataPath;  //数据目录  
  4.     string url = AppConst.WebUrl + AppConst.AppName + "/";  
  5.     string listUrl = url + "files.txt";  
  6.     WWW www = new WWW(listUrl); yield return www;  
  7.     if (www.error != null)  
  8.     {  
  9.         yield break;  
  10.     }  
  11.     if (!Directory.Exists(dataPath))  
  12.     {  
  13.         Directory.CreateDirectory(dataPath);  
  14.     }  
  15.     File.WriteAllBytes(dataPath + "files.txt", www.bytes);  
  16.     string filesText = www.text;  
  17.     string[] files = filesText.Split('\n');  
  18.   
  19.     for (int i = 0; i < files.Length; i++)  
  20.     {  
  21.         if (string.IsNullOrEmpty(files[i]))  
  22.         {  
  23.             continue;  
  24.         }  
  25.         string[] keyValue = files[i].Split('|');  
  26.         string f = keyValue[0];  
  27.         string localfile = (dataPath + f).Trim();  
  28.         string path = Path.GetDirectoryName(localfile);  
  29.         if (!Directory.Exists(path))  
  30.         {  
  31.             Directory.CreateDirectory(path);  
  32.         }  
  33.         string fileUrl = url + f;  
  34.         bool canUpdate = !File.Exists(localfile);  
  35.         if (!canUpdate)  
  36.         {  
  37.             string remoteMd5 = keyValue[1].Trim();  
  38.             string localMd5 = Util.md5file(localfile);  
  39.             canUpdate = !remoteMd5.Equals(localMd5);  
  40.             if (canUpdate)  
  41.             {  
  42.                 File.Delete(localfile);  
  43.             }  
  44.         }  
  45.         if (canUpdate)  
  46.         {     
  47.             //这里都是资源文件,用线程下载  
  48.             BeginDownload(fileUrl, localfile);  
  49.         }  
  50.     }  
  51.   
  52.     while (!updateWorker.IsDownFinish())  
  53.     {  
  54.         yield return new WaitForEndOfFrame();  
  55.     }  
  56.     yield return new WaitForEndOfFrame();  
  57.     StartGame();  
  58. }  

这些都准备好之后,我们需要一个web服务器,到http://nginx.org/下载一个nginx,并把生成的Assetbundle拷到其目录下的


启动nginx,导出一个apk包,运行就可以看到效果了。

题外话,android 下热更dll不能用这种方式,5x的打包方去加载dll的Assetbundle会是空的,要用4.x打包方式,如果有人知道5.x怎么弄,求告知

BuildPipeline.BuildAssetBundle(mainAsset, null, Application.dataPath + "mydll.assetbundle",
                               BuildAssetBundleOptions.None,BuildTarget.Android);

        WWW www = new WWW(url);

        yield return www;

        if(www.error != null)
        {
            Debug.Log("加载 出错");
        }

        if(www.isDone)
        {
            Debug.Log("加载完毕");
            AssetBundle ab = www.assetBundle;

            try
            {
                Assembly aly = System.Reflection.Assembly.Load(((TextAsset)www.assetBundle.mainAsset).bytes);

                foreach (var i in aly.GetTypes())
                {
                    //调试代码
                    Debug.Log(i.Name);
                    Component c = this.gameObject.AddComponent(i);
                }
            }
            catch (Exception e) 
            {
                Debug.Log("加载DLL出错");
                Debug.Log(e.Message);
            }
        }

最后附上工程项目 https://github.com/caolaoyao/AutoUpdateAssetBundle

主要参考:http://unity3d.com/cn/node/17559


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值