Unity3d为ulua提供更新的接口
2014-12-27 16:21
218 查看
/// <summary> /// 写入资源. /// </summary> /// <param name="filepath">Filepath.</param> /// <param name="luafunc">Lua回调函数.</param> public void WriteAssetBundleToLocal(string filepath,System.Object luafunc){ StartCoroutine (WriteToLocal (filepath,luafunc)); } IEnumerator WriteToLocal(string filepath,System.Object luafunc){ string insidepath = ""; string extensionname = ""; extensionname = FileHelper.GetFileExtensionName (filepath); //int num = Regex.Matches(filepath,@".").Count; insidepath = FileHelper.CreateFilePathBySubString (filepath, 2); insidepath = insidepath.Replace (".", "/"); filepath = FileHelper.CreateFilePathBySubString (filepath,1); //print ("filepath=" + filepath); filepath = filepath.Replace (".", "/"); filepath = filepath + extensionname; //print ("filepath="+filepath); if (Application.platform == RuntimePlatform.Android) { string path = readpath + filepath; WWW assetbundle = new WWW (path); yield return assetbundle; byte[] module; int length; if(assetbundle.error!=null){ iserrorhappen =true; module = assetbundle.bytes; length = module.Length; System.IO.Directory.CreateDirectory(writepath+filepath); //print ("CreateDirectory="+writepath+filepath); CreateModuleFile (writepath, filepath,module,length, luafunc); } if (assetbundle.isDone) { module = assetbundle.bytes; FileHelper.CreateDirectory ("/storage/sdcard0/" + insidepath); FileHelper.DeleteFile ("/storage/sdcard0/"+ filepath); //stringToEdit+= System.IO.Directory.Exists("/storage/sdcard0/"+filepath)+"\n"; //System.IO.Directory.CreateDirectory("/storage/sdcard0/"+insidepath); //if(System.IO.Directory.Exists("/storage/sdcard0/"+filepath)) //System.IO.Directory.Delete("/storage/sdcard0/"+filepath+"/",true); stringToEdit += "/storage/sdcard0/" + insidepath +"\n"; length = module.Length; //stringToEdit += " assetbundle.isDone" +"\n"; //stringToEdit += "/storage/sdcard0/"+filepath + "\n"; //print ("assetbundle.isDone"); CreateModuleFile (writepath, filepath, module, length, luafunc); } } else if (Application.platform == RuntimePlatform.WindowsEditor) { print ("assetbundle.length=="+readpath + filepath); byte[] module = File.ReadAllBytes (readpath + filepath); int length = module.Length; //print ("assetbundle.length=="+length); FileHelper.CreateDirectory (Application.persistentDataPath + "/" + insidepath); FileHelper.DeleteFile (Application.persistentDataPath+"/" + filepath); CreateModuleFile (Application.persistentDataPath, filepath, module, length, luafunc); } else if (Application.platform == RuntimePlatform.OSXEditor) { byte[] module = File.ReadAllBytes (readpath+ filepath); int length = module.Length; print ("assetbundle.length=="+length); FileHelper.CreateDirectory (Application.persistentDataPath + "/" + insidepath); FileHelper.DeleteFile (Application.persistentDataPath+"/" + filepath); CreateModuleFile (Application.persistentDataPath, filepath, module, length, luafunc); } else if (Application.platform == RuntimePlatform.IPhonePlayer) { byte[] module = File.ReadAllBytes (readpath + filepath); int length = module.Length; print ("assetbundle.length=="+length); FileHelper.CreateDirectory (Application.persistentDataPath + "/" + insidepath); FileHelper.DeleteFile (Application.persistentDataPath+"/" + filepath); CreateModuleFile (Application.persistentDataPath, filepath, module, length, luafunc); } else if (Application.platform == RuntimePlatform.WindowsPlayer) { print ("assetbundle.length=="+readpath + filepath); byte[] module = File.ReadAllBytes (readpath + filepath); int length = module.Length; //print ("assetbundle.length=="+length); FileHelper.CreateDirectory (Application.persistentDataPath + "/" + insidepath); FileHelper.DeleteFile (Application.persistentDataPath+"/" + filepath); CreateModuleFile (Application.persistentDataPath, filepath, module, length, luafunc); } else { print ("Platform error"); } } /// <summary> /// Downs the load source form server. /// </summary> /// <param name="name">资源名称.</param> /// <param name="url">下载地址.</param> /// <param name="luafunc">lua回调函数.</param> public void DownLoadSourceFormServer(string name,string url,System.Object luafunc){ StartCoroutine (DownLoadFormServer(name,url,luafunc)); } public IEnumerator DownLoadFormServer(string name,string url,System.Object luafunc){ string extensionname = ""; extensionname = FileHelper.GetFileExtensionName (name); if(name.Contains(".")){ string creatfilepath= FileHelper.CreateFilePathBySubString(name,2);//name.Substring(0,name.IndexOf(".")); creatfilepath = creatfilepath.Replace(".","/"); FileHelper.CreateDirectory(writepath+"/"+creatfilepath); } isindownload = true; name = FileHelper.CreateFilePathBySubString(name,1);// name =name.Replace (".","/"); stringToEdit +="Download=="+ name + "\n"; FileHelper.DeleteFile (writepath+"/"+name+extensionname); assetbundle = new WWW (url); yield return assetbundle; print(url); if(assetbundle.error!=null){ print(name); print ("SERVER ERROR"+assetbundle.error.ToString()); byte[] model =null; int length =0; string filepath=name+extensionname; iserrorhappen =true; Global.loadLoginScence(); //FileHelper.DeleteFile (writepath+ "/"+name+extensionname); //print("WRONG=="+writepath+ "/"+name+extensionname); //CreateModuleFile (writepath, filepath, model, length,luafunc); }else if(assetbundle.isDone){ byte[] model =assetbundle.bytes; int length =model.Length; string filepath=name+extensionname; //stringToEdit +="filepath=="+ filepath + "\n"; FileHelper.DeleteFile (writepath+ "/"+name+extensionname); CreateModuleFile (writepath, filepath, model, length,luafunc); } } /// <summary> /// Raises the init lua scripts event. /// </summary> /// <param name="scriptname">脚本名字.</param> /// <param name="assetbundlename">脚本所在资源.</param> /// <param name="functionname">回掉函数名字.</param> public void OnInitLuaScripts(string scriptname,string assetbundlename,string functionname){ StartCoroutine (InitLuaScripts(scriptname,assetbundlename,functionname)); } IEnumerator InitLuaScripts(string scriptname,string assetbundlename,string functionname){ if(assetbundlename.Contains(".")){ assetbundlename = assetbundlename.Replace (".","/"); assetbundlename = assetbundlename.Replace("/assetbundle",""); } //print ("InitLuaScripts-assetbundlename=="+assetbundlename); //stringToEdit += "InitLua=="+assetbundlename + "\n"; Resources.UnloadUnusedAssets (); byte[] stream; string filepath =writepath+"/"+assetbundlename+".assetbundle"; print ("filepath=="+filepath); AssetBundleCreateRequest request; stream = File.ReadAllBytes (filepath); //stringToEdit += stream.Length + "\n"; request = AssetBundle.CreateFromMemory (stream); yield return request; luascriptbundle = request.assetBundle; //print ("scriptname=="+scriptname); TextAsset luaconfigure = luascriptbundle.Load (scriptname) as TextAsset; //print ("script=="+luaconfigure.text); iLua.DoString (luaconfigure.text,luaconfigure.name.ToString(),null); stringToEdit += scriptname + "\n"; if (functionname != "0") { LuaFunction OnInitialize = iLua.GetFunction (functionname); object [] res = OnInitialize.Call (); luascriptbundle.Unload (false); } else { luascriptbundle.Unload (false); } } /// <summary> /// 写本地文件 /// </summary> /// <param name="path">Path.</param> /// <param name="name">Name.</param> /// <param name="info">Info.</param> /// <param name="length">Length.</param> /// <param name="luafunc">lua回调函数.</param> void CreateModuleFile(string path,string name,byte[] info,int length,System.Object luafunc){ //print (path + "//" + name); //print ("iserrorhappen=="+iserrorhappen); //System.IO.Directory.Delete(path + "//" + name,true); if (!iserrorhappen) { FileInfo t = new FileInfo (path + "/" + name); //stringToEdit +="t.Exists=="+ t.Exists + "\n"; if (!t.Exists) { sw = t.Create (); } else { stringToEdit +="CreateModuleFile Wrong=="+ t.Exists + "\n"; return; } sw.Write (info, 0, length); sw.Close (); sw.Dispose (); //if(assetbundle!=null) //assetbundle.assetBundle.Unload(false); //stringToEdit +="Create over==" + "\n"; } if (luafunc != null) { LuaInterface.LuaFunction func = (LuaInterface.LuaFunction)luafunc; if(iserrorhappen){// iserrorhappen =false; func.Call (iserrorhappen);//iserrorhappen=false } else{ //stringToEdit +="func=="+func.ToString()+ "\n"; func.Call (!iserrorhappen);//!iserrorhappen=true } } else { ishavewrite =true; isfirstrun =!isfirstrun; print ("000000000"+isfirstrun); //stringToEdit +="StartUpdateFlow"+ "\n"; StartUpdateFlow(); } } public string GetFileMd5(string filepath){ string extersionname = FileHelper.GetFileExtensionName (filepath); filepath = FileHelper.CreateFilePathBySubString (filepath,1); filepath =filepath.Replace(".","/"); filepath =writepath+"/"+filepath+extersionname; FileInfo t = new FileInfo (filepath); if (t.Exists) return FileHelper.md5file (filepath); else return "0"; } public void DecompressFile(string filepath,System.Object luafunc){ //print ("filepath*-*-*-"+filepath); //Assetbundle.picAtlas.picAtlas.zip string inpath = ""; inpath = FileHelper.CreateFilePathBySubString (filepath,1); inpath = inpath.Replace (".","/"); string outpath =writepath+ "/"+inpath ;//+ "1.assetbundle"; outpath = outpath.Replace(".","/"); FileHelper.DeleteFile (outpath+".assetbundle"); print ("删除旧的assetbundle"); outpath=outpath+".assetbundle"; inpath = writepath+ "/"+inpath + ".zip";//FileHelper.GetFileExtensionName(filepath); FileHelper.DecompressFileLZMA (inpath, outpath); LuaInterface.LuaFunction func = (LuaInterface.LuaFunction)luafunc; if(luafunc!=null){ func.Call (); } }
上面都是提供给ulua使用的cs接口函数,我这样就在lua里面直接使用了
里面有一个FileHelper脚本主要写了一些对文件操作的辅助函数,哈哈
using UnityEngine; using System.Collections; using System.IO; using System.Collections.Generic; using System.Text; using System; using SevenZip.Compression.LZMA; public class FileHelper { /// <summary> /// 删除文件 /// </summary> /// <param name="path">Path.</param> /// <param name="name">Name.</param> public static void DeleteFile(string path) { File.Delete(path); } /// <summary> /// 删除指定目录及其所有子目录 /// </summary> /// <param name="directoryPath">指定目录的绝对路径</param> public static void DeleteDirectory(string directoryPath) { if (IsExistDirectory(directoryPath)) { Directory.Delete(directoryPath, true); } } /// <summary> /// Creates the directory. /// </summary> /// <param name="directoryPath">Directory path.</param> public static void CreateDirectory(string directoryPath) { //如果目录不存在则创建该目录 if (!IsExistDirectory(directoryPath)) { //Debug.Log("path doesnot exit"); Directory.CreateDirectory(directoryPath); } } public static bool IsExistDirectory(string directoryPath) { return Directory.Exists(directoryPath); } /// <summary> /// Md5file the specified file. /// </summary> /// <param name="file">File.</param> public static string md5file(string file) { try { FileStream fs = new FileStream(file, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(fs); fs.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("md5file() fail, error:" + ex.Message); } } public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild) { //Debug.Log(directoryPath); //如果目录不存在,则抛出异常 if (!IsExistDirectory(directoryPath)) { throw new FileNotFoundException(); } try { if (isSearchChild) { return Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories); } else { return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly); } } catch (IOException ex) { throw ex; } } /// <summary> /// 获取指定目录中所有文件列表 /// </summary> /// <param name="directoryPath">指定目录的绝对路径</param> public static string[] GetFileNames(string directoryPath) { //如果目录不存在,则抛出异常 if (!IsExistDirectory(directoryPath)) { throw new FileNotFoundException(); } //获取文件列表 return Directory.GetFiles(directoryPath); } /// <summary> /// 生成一个Key名 /// </summary> public static string GetKey(string key) { //return Const.AppPrefix + Const.UserId + "_" + key; return Application.platform.ToString () + "_" + key; } /// <summary> /// 取得整型 /// </summary> public static int GetInt(string key) { string name = GetKey(key); return PlayerPrefs.GetInt(name); } /// <summary> /// 有没有值 /// </summary> public static bool HasKey(string key) { string name = GetKey(key); return PlayerPrefs.HasKey(name); } /// <summary> /// 保存整型 /// </summary> public static void SetInt(string key, int value) { string name = GetKey(key); PlayerPrefs.DeleteKey(name); PlayerPrefs.SetInt(name, value); } /// <summary> /// 取得数据 /// </summary> public static string GetString(string key) { string name = GetKey(key); return PlayerPrefs.GetString(name); } /// <summary> /// 保存数据 /// </summary> public static void SetString(string key, string value) { string name = GetKey(key); PlayerPrefs.DeleteKey(name); PlayerPrefs.SetString(name, value); } /// <summary> /// 删除数据 /// </summary> public static void RemoveData(string key) { string name = GetKey(key); PlayerPrefs.DeleteKey(name); } /// <summary> /// 清理内存 /// </summary> public static void ClearMemory() { GC.Collect(); Resources.UnloadUnusedAssets(); } public static void CreateModuleFile(string writepath,string name,byte[] info,int length){ //Debug.Log (writepath + "//" + name); Stream sw = null; FileInfo t = new FileInfo (writepath + "/" + name); //stringToEdit +="t.Exists=="+ t.Exists + "\n"; if (!t.Exists) { sw = t.Create (); } else { return; } sw.Write (info, 0, length); sw.Close (); sw.Dispose (); } public static string CreateFilePathBySubString(string fullpath,int subtimes){ //string firstsub = fullpath.Substring (0,fullpath.LastIndexOf(".")); //string secondsub = firstsub.Substring (0,firstsub.LastIndexOf(".")); //Debug.Log ("fullpath="+fullpath); string inpath = ""; inpath= fullpath; int time = subtimes; if (time == 0) { inpath= fullpath; } else { for(int i=0;i<time;i++){ inpath = inpath.Substring (0,inpath.LastIndexOf(".")); } } return inpath; } public static string GetFileExtensionName(string filefullpath){ string extensionname = ""; //Debug.Log ("filefullpath--"+filefullpath); extensionname = filefullpath.Substring (filefullpath.LastIndexOf(".")+1); //Debug.Log ("extensionname++"+extensionname); extensionname = "." + extensionname; return extensionname; } public static void CompressFileLZMA(string inFile, string outFile) { SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder(); FileStream input = new FileStream(inFile, FileMode.Open); FileStream output = new FileStream(outFile, FileMode.Create); // Write the encoder properties coder.WriteCoderProperties(output); // Write the decompressed file size. output.Write(BitConverter.GetBytes(input.Length), 0, 8); // Encode the file. coder.Code(input, output, input.Length, -1, null); output.Flush(); output.Close(); input.Close(); } public static void DecompressFileLZMA(string inFile, string outFile) { SevenZip.Compression.LZMA.Decoder coder = new SevenZip.Compression.LZMA.Decoder(); FileStream input = new FileStream(inFile, FileMode.Open); FileStream output = new FileStream(outFile, FileMode.Create); // Read the decoder properties byte[] properties = new byte[5]; input.Read(properties, 0, 5); // Read in the decompress file size. byte [] fileLengthBytes = new byte[8]; input.Read(fileLengthBytes, 0, 8); long fileLength = BitConverter.ToInt64(fileLengthBytes, 0); // Decompress the file. coder.SetDecoderProperties(properties); coder.Code(input, output, input.Length, fileLength, null); output.Flush(); output.Close(); input.Close(); } public static long GetFileLength(string filepath){ if (!System.IO.Directory.Exists(filepath)) return 0; string[] fs = System.IO.Directory.GetFiles(filepath, "*.*", System.IO.SearchOption.AllDirectories); //获取该文件夹中所有的文件名 long ll = 0; foreach (string f in fs) { if(f.Contains(".meta"))continue; dynamic fa = System.IO.File.GetAttributes(f); System.IO.FileInfo fi = new System.IO.FileInfo(f); ll += fi.Length; } return ll; } }
由于我自己打出来的资源包非常的大,于是我就采用了LAMZ压缩算法,对资源包进行了压缩,还可以,只是客户端解压的时候会卡一些。。。
相关文章推荐
- unity3d热更新插件uLua学习整理
- Unity3D 调用Android的提供的接口
- unity3d热更新插件uLua
- unity3d热更新插件uLua学习整理
- unity3d热更新插件uLua学习整理
- Unity3D调用Android提供的接口
- [Java] JDBC 08 处理可更新的结果集 (sun提供了这样的接口,但是不见得所有的数据库厂商都支持)
- JAVA EXCEL API简介+应用示例+Workbook类提供的方法 +Sheet接口提供的方法 +生成新的Excel工作薄+拷贝、更新Excel工作薄
- unity3d热更新插件uLua学习整理
- [Java] JDBC 08 处理可更新的结果集 (sun提供了这样的接口,但是不见得所有的数据库厂商都支持)
- unity3d热更新插件uLua学习整理
- 苹果提供的更新以及后台接口绕过审核的更新
- unity3d热更新插件uLua学习整理
- unity3d热更新插件uLua学习整理
- Unity3D热更新:ULua && Simpleframework环境安装详解
- 站点维护使用app_offline.htm页面提供友好的更新提示
- Unity3D NGUI自适应屏幕分辨率(2014/4/17更新)
- unity3d 理解刚体(Rigidbody)和碰撞体(Collider)以及触发器(Is Trigger),边学边更新
- (8)Launcher3客制化之ContentProvider内容提供者,实现其他应用修改数据库更新等操作
- 整理一些Unity3d的资源 C# 相关(不断更新中)