Пример #1
0
    public void BuildWithByteCode(string outputDir,string[] inputs,BuildTarget targetPlatform)
    {
        if(!System.IO.Directory.Exists(outputDir)){
            System.IO.Directory.CreateDirectory(outputDir);
        }

        ShellHelper.ShellRequest req =  Compile(inputs);
        req.onDone += delegate() {
            AssetDatabase.Refresh();
            List<AssetBundleBuild> buildInfos = new List<AssetBundleBuild>();
            foreach(string input in inputs){
                string bundleName = System.IO.Path.GetFileName(input);
                string[] luaFiles = System.IO.Directory.GetFiles(input,"*.lua.txt", System.IO.SearchOption.AllDirectories);
                AssetBundleBuild bd = new AssetBundleBuild();
                bd.assetBundleName = bundleName;
                bd.assetNames = luaFiles;
                buildInfos.Add(bd);
            }

            AssetDatabase.Refresh();

            BuildPipeline.BuildAssetBundles(outputDir,buildInfos.ToArray(),BuildAssetBundleOptions.None,targetPlatform);
            //delete temp files ,
            foreach(AssetBundleBuild bd in buildInfos){
                foreach(string file in bd.assetNames){
                    FileUtil.DeleteFileOrDirectory(file);
                }
            }
            string outputDirName = System.IO.Path.GetFileName(outputDir);
            RenameFile(outputDir+"/"+outputDirName,outputDir+"/LuaPlugins");
            RenameFile(outputDir+"/"+outputDirName+".manifest",outputDir+"/LuaPlugins.manifest");

            AssetDatabase.Refresh();
        };
    }
Пример #2
0
    public static void BuildAssetBundlesBatch()
    {
        // Choose the output path according to the build target.
        string outputPath = Path.Combine(kAssetBundlesOutputPath,  BaseLoader.GetPlatformFolderForAssetBundles(EditorUserBuildSettings.activeBuildTarget) );
        if (!Directory.Exists(outputPath) )
            Directory.CreateDirectory (outputPath);

        string [] args = System.Environment.GetCommandLineArgs();
        Debug.Log ( "ARGS:" + args[9] );
        int startRatio = int.Parse(args[9]);
        int endRatio   = int.Parse(args[10]);
        string [] allAssetBundleNames = AssetDatabase.GetAllAssetBundleNames();
        int counter = allAssetBundleNames.Length * startRatio / 100;
        int counter_end = allAssetBundleNames.Length * endRatio / 100;
        Debug.Log ("Build " + counter + "/" + allAssetBundleNames.Length + " -> " + (counter_end-1) + "/" + allAssetBundleNames.Length );
        AssetBundleBuild[] buildMap = new AssetBundleBuild[counter_end - counter];
        int num = 0;
        for( int i=counter ; i<counter_end ; i++ ) {
            string abname = allAssetBundleNames[i];

            buildMap[num].assetBundleName = abname;
            buildMap[num].assetNames = AssetDatabase.GetAssetPathsFromAssetBundle(abname);
            num++;
        }
        BuildPipeline.BuildAssetBundles (outputPath, buildMap, 0, EditorUserBuildSettings.activeBuildTarget);
    }
Пример #3
0
 /// <summary>
 /// 自动构建ab
 /// </summary>
 /// <param name="assets"></param>
 /// <param name="outPath"></param>
 /// <param name="abName"></param>
 /// <param name="bbo"></param>
 public static void BuildABs(string[] assets, string outPath, string abName, BuildAssetBundleOptions bbo)
 {
     AssetBundleBuild[] bab = new AssetBundleBuild[1];
     bab[0].assetBundleName = abName;//打包的资源包名称 随便命名
     bab[0].assetNames = assets;
     if (string.IsNullOrEmpty(outPath))
         outPath = GetOutPutPath();
     BuildPipeline.BuildAssetBundles(outPath, bab, bbo, target);
 }
Пример #4
0
 private static void BuildBundle(List<string> prefabPaths)
 {
     AssetBundleBuild[] buildInfo = new AssetBundleBuild[1];
     buildInfo[0] = new AssetBundleBuild
     {
         assetBundleName = ASSET_BUNDLE_NAME,
         assetNames = prefabPaths.ToArray()
     };
     BuildPipeline.BuildAssetBundles(ASSET_BUNDLE_OUTPUT_PATH,buildInfo,BuildAssetBundleOptions.None, BuildTarget.WebGL);
 }
	// 在Unity编辑器中添加菜单,导出的时候,一定要先选择自己设置的预设,然后点击菜单,支持选中文件夹,导出选中的资源到一个文件
    //[MenuItem("Assets/Build AssetBundle From Selection All - Track dependencies")]
    static void ExportAssetBundlesAll()
	{
		// 打开保存面板,获得用户选择的路径  
        string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
        //EditorUtility.GetAssetPath
        //EditorUtility.InstanceIDToObject
        //EditorUtility.CreateGameObjectWithHideFlags
		
		if (path.Length != 0)
		{  
			// 选择的要保存的对象  
			Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets); 
			//打包  
            //BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.StandaloneWindows);

#if UNITY_5
            List<string> assetNameList = new List<string>();
            string nameStr;
            foreach (Object item in selection)
            {
                nameStr = AssetDatabase.GetAssetPath(item);
                nameStr = nameStr.Substring(nameStr.IndexOf("Assets"), nameStr.Length - nameStr.IndexOf("Assets"));
                assetNameList.Add(nameStr);
            }

            AssetBundleBuild[] buildList = new AssetBundleBuild[1];
            buildList[0].assetBundleName = "SavePrefab";
            buildList[0].assetBundleVariant = "unity3d";
            buildList[0].assetNames = assetNameList.ToArray();
            BuildPipeline.BuildAssetBundles(path, buildList, 0, BuildTarget.StandaloneWindows);
#elif UNITY_4_6 || UNITY_4_5
            BuildPipeline.BuildAssetBundle(null, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.UncompressedAssetBundle, BuildTarget.StandaloneWindows);
#endif
            Selection.objects = selection;
            //FileStream fs = File.Open(path + ".log", FileMode.OpenOrCreate);
            //StreamWriter sw = new StreamWriter(fs);
            //sw.WriteLine("文件 " + path + " 中的内容如下:");
            foreach (Object obj in Selection.objects)
            {
                //sw.WriteLine("Name: " + obj.name + " Type:" + obj.GetType());
                if (obj.GetType() == typeof(Object))
                {
                    Debug.LogWarning("Name: " + obj.name + ", Type: " + obj.GetType() + ". 可能是unity3d不能识别的文件,可能未被打包成功");
                }
            }
            //sw.Flush();
            //fs.Flush();
            //sw.Close();
            //fs.Close();
		}

        System.GC.Collect();
	}
Пример #6
0
 static void GenerateAssetBundleIOS()
 {
     Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.Assets);
     string [ ] assetNames = new string [ selection. Length ] ;
     int i = 0 ;
     foreach ( UnityEngine. Object o in selection )
     {
         assetNames [ i ++ ] = AssetDatabase . GetAssetPath ( o ) ;
     }
     AssetBundleBuild [ ] buildMap = new AssetBundleBuild [ 1 ] ;
     buildMap [ 0 ] = new AssetBundleBuild ( ) ;
     buildMap [ 0 ] . assetBundleName = "IOSBundle"; //mBundleId. ToString ( ) ;
     buildMap [ 0 ] . assetNames = assetNames;
     BuildPipeline . BuildAssetBundles ( "Assets/AssetsIOS" , buildMap, BuildAssetBundleOptions. CollectDependencies | BuildAssetBundleOptions. CompleteAssets , BuildTarget.iOS) ;
 }
Пример #7
0
    public static void AutoPackAsset()
    {
        Object[] ojbs = Selection.objects;
        int count = ojbs.Length;
        AssetBundleBuild[] builds = new AssetBundleBuild[count];
        for (int i = 0; i<count; i++) {
            string packPath = AssetDatabase.GetAssetPath (ojbs [i]);
            builds [i].assetBundleName = "packed" + ojbs [i].name;

            string[] assetsNames = new string[1];
            assetsNames [0] = packPath;

            builds [i].assetNames = assetsNames;
        }

        BuildPipeline.BuildAssetBundles (Application.dataPath + "/PackedAssets", builds);
    }
    //[MenuItem("热更打包/Build Asset Bundles")]
    static void BuildABs()
    {
        AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
        buildMap[0].assetBundleName = "prefabBundles";
        string[] names = {
            "Assets/Prefabs/Capsule.prefab",
            "Assets/Prefabs/Cube.prefab"};
        buildMap[0].assetNames = names;
        /*
        buildMap[1].assetBundleName = "sceneBundles";
        string[] names2 = {
            "Assets/Scenes/scene.unity"};
        buildMap[1].assetNames = names2;
        */

        BuildPipeline.BuildAssetBundles("Assets/Abs", buildMap);
    }
Пример #9
0
    private void BuildElement(string folder, string elementName, string bundlesGroupIdentifier)
    {
        var names = AssetDatabase.GetAllAssetBundleNames();

        foreach (var n in names)
        {
            Debug.Log("Name = " + n);

            AssetBundleBuild abb = new AssetBundleBuild
            {
                assetBundleName = n
            };

            string path = "Bundles/" + folder + "/";
            Directory.CreateDirectory(path);

            BuildPipeline.BuildAssetBundles(path, new []{abb});
        }


    }
Пример #10
0
    static void TestBuildAB()
    {
        var buildMap = new AssetBundleBuild[3];

        // set bundle name and contained contents to map for No 0.
        {
            var paths = new string[1];
            paths[0] = "Assets/AssetBundleSample/SampleAssets/MyCube.prefab";

            buildMap[0].assetBundleName = "mycube-bundle";
            buildMap[0].assetNames = paths;
        }

        // No 1.
        {
            var paths = new string[1];
            paths[0] = "Assets/AssetBundleSample/SampleAssets/MyMaterial.mat";

            buildMap[1].assetBundleName = "mymat-bundle";
            buildMap[1].assetNames = paths;
        }

        // No 2.
        {
            var paths = new string[2];
            paths[0] = "Assets/AssetBundleSample/SampleAssets/UnityLogo.png";

            buildMap[2].assetBundleName = "mypic-bundle";
            buildMap[2].assetNames = paths;
        }

        // Choose the output path according to the build target.
        string outputPath = Path.Combine(Utility.AssetBundlesOutputPath,  Utility.GetPlatformName());
        if (!Directory.Exists(outputPath) )
            Directory.CreateDirectory (outputPath);

        BuildPipeline.BuildAssetBundles(outputPath, buildMap, BuildAssetBundleOptions.None, BuildTarget.StandaloneOSXIntel);
    }
Пример #11
0
    static void CreateResources()
    {
        //// 选择的要保存的对象  4.x
        //Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        ////打包
        //BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.StandaloneWindows);

        AssetBundleBuild[] buildMap = new AssetBundleBuild[2];

        var basePath = Application.dataPath + ExportConfigWindow.EXPORT_PREFABS_PATH.Substring(6);

        List<string> prefabs = new List<string>();
        forEachHandle(basePath, "prefab", (string filename) =>
        {
            prefabs.Add(ExportConfigWindow.EXPORT_PREFABS_PATH + filename.Replace(basePath, "").Replace(@"\","/"));
        });

        buildMap[0].assetBundleName = "prefabBundles";
        buildMap[0].assetNames = prefabs.ToArray();

        basePath = Application.dataPath + ExportConfigWindow.EXPORT_SCENE_PATH.Substring(6);

        List<string> scenes = new List<string>();
        forEachHandle(basePath, "unity", (string filename) =>
        {
            scenes.Add(ExportConfigWindow.EXPORT_SCENE_PATH + filename.Replace(basePath, "").Replace(@"\", "/"));
        });

        buildMap[1].assetBundleName = "sceneBundles";
        buildMap[1].assetNames = scenes.ToArray();

        BuildPipeline.BuildAssetBundles("Assets/StreamingAssets", buildMap,BuildAssetBundleOptions.ChunkBasedCompression, ExportConfigWindow.BUILD_TARGET);
        // BuildPipeline.BuildAssetBundles("Assets/StreamingAssets");
        AssetDatabase.Refresh();

        Debug.Log("AssetBundles 打包完成 位于:Assets/StreamingAssets");
    }
Пример #12
0
    // 打包自己在 Project 窗口中选择的资源
    public static void BuildSelectAssetBundles()
    {
        string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
        string fileName = "";
        string extName = "";

        path = ExportUtil.normalPath(path);

        int lastSlashIdx = 0;
        int dotIdx = 0;

        lastSlashIdx = path.LastIndexOf("/");
        dotIdx = path.LastIndexOf(".");

        fileName = path.Substring(lastSlashIdx + 1, dotIdx - lastSlashIdx - 1);
        extName = path.Substring(dotIdx + 1, path.Length - dotIdx - 1);
        path = path.Substring(0, lastSlashIdx);

        if (path.Length != 0)
        {
            List<string> assetNameList = new List<string>();
            string nameStr;
            foreach (Object item in Selection.objects)
            {
                nameStr = AssetDatabase.GetAssetPath(item);
                nameStr = nameStr.Substring(nameStr.IndexOf("Assets"), nameStr.Length - nameStr.IndexOf("Assets"));
                assetNameList.Add(nameStr);
            }

            AssetBundleBuild[] buildList = new AssetBundleBuild[1];
            buildList[0].assetBundleName = fileName;
            buildList[0].assetBundleVariant = extName;
            buildList[0].assetNames = assetNameList.ToArray();
            BuildPipeline.BuildAssetBundles(path, buildList, 0, BuildTarget.StandaloneWindows);
        }
    }
Пример #13
0
    //[MenuItem("Assets/Language Asset Export", false,2)]
    //static void ExportTextAsset()
    //{
    //    Object[] selection = Selection.objects;
    //    foreach (Object obj1 in selection)
    //    {
    //        if (obj1 is UnityEngine.TextAsset)
    //        {
    //            BuildTextAsset(obj1);
    //        }
    //    }
    //}

    #endregion Other

    #if UNITY_5

    //[MenuItem("Assets/AssetBundle Build BySelect", false, 2)]
    public static void BuildAssetBundle()
    {
        List<AssetBundleBuild> abs = new List<AssetBundleBuild>();
           Object[] selection = Selection.objects;

        foreach (Object s in selection)
        {
            if (s is GameObject)
            {
                AssetBundleBuild ab = new AssetBundleBuild();
                ab.assetBundleName = s.name;
                var assets = new string[1];
                assets[0] = s.name;
                ab.assetNames = assets;

                Debug.Log(ab.assetNames[0]);
                abs.Add(ab);
            }
         }

        Debug.Log(abs.Count);

        BuildPipeline.BuildAssetBundles(getOutPutPath(target), abs.ToArray());
    }
Пример #14
0
    static void BuildAllAssetBundlesMerged()
    {
        /*
         * Build a single asset bundle from selected folder of prefabs.
         */
        string defaultName = "default_bundle.bundle";
        // Build all bundles existing in the project
        //		BuildPipeline.BuildAssetBundles ("Assets/AssetBundles/", BuildAssetBundleOptions.None, BuildTarget.StandaloneOSXUniversal);
        // For building bundles selectively
        Dictionary<GameObject, string> selectedPrefabs = ListSelectedPrefabs ();
        AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
        string[] assetPath = new string[selectedPrefabs.Count];

        int loop_counter = 0;
        foreach (KeyValuePair<GameObject, string> entry in selectedPrefabs) {
            assetPath [loop_counter] = entry.Value;
            loop_counter++;
        }
        buildMap [0].assetBundleName = defaultName;
        buildMap [0].assetNames = assetPath;
        BuildPipeline.BuildAssetBundles ("Assets/PrefabDatabase/AssetBundles/Merged",
            buildMap,
            BuildAssetBundleOptions.None,
            BuildTarget.StandaloneOSXUniversal
        );
    }
Пример #15
0
 internal AssetBundleBuild CreateUniqueBundle(AssetBundleBuild bid)
 {
     return(CreateUniqueBundle(bid, m_BundleToAssetGroup));
 }
Пример #16
0
        public override void Export()
        {
            #region 源代码
            base.Export();

            var platform = PathResolver.GetPlatformName();
            var filePath = Path.Combine(Path.Combine(Environment.CurrentDirectory, PathResolver.BundleSaveDirName), platform).Replace("\\", "/") + "/";
            if (Directory.Exists(filePath))
            {
                Directory.Delete(filePath, true);
            }
            Directory.CreateDirectory(filePath);

            List <AssetBundleBuild> list = new List <AssetBundleBuild>();
            //标记所有 asset bundle name
            var all = AssetBundleUtils.GetAll();
            for (int i = 0; i < all.Count; i++)
            {
                AssetTarget target = all[i];
                if (target.needSelfExport)
                {
                    AssetBundleBuild build = new AssetBundleBuild();
                    build.assetBundleName = target.bundleName;
                    build.assetNames      = new string[] { target.assetPath };
                    list.Add(build);
                }
            }

            //开始打包
            BuildPipeline.BuildAssetBundles(
                PathResolver.BundleSavePath,
                list.ToArray(),
                BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.DeterministicAssetBundle,
                EditorUserBuildSettings.activeBuildTarget);

#if UNITY_5_1 || UNITY_5_2
            AssetBundle ab = AssetBundle.CreateFromFile(PathResolver.BundleSavePath + PathResolver.GetPlatformForAssetBundles(Application.platform));
#else
            var ab = AssetBundle.LoadFromFile(PathResolver.BundleSavePath + "/" + PathResolver.GetPlatformName());
#endif
            var manifest = ab.LoadAsset("AssetBundleManifest") as AssetBundleManifest;
            //hash
            for (int i = 0; i < all.Count; i++)
            {
                AssetTarget target = all[i];
                if (target.needSelfExport)
                {
                    Hash128 hash = manifest.GetAssetBundleHash(target.bundleName);
                    target.bundleCrc = hash.ToString();
                }
            }

            this.SaveDepAll(all);
            this.SaveSpriteAll(all);
            this.SaveAssetAll(all);
            this.ExportResourcesManifestFile(manifest);
            ab.Unload(true);
            this.RemoveUnused(all);


            AssetDatabase.RemoveUnusedAssetBundleNames();
            AssetDatabase.Refresh();

            Debug.Log("[Assets]Build Finish!");
            #endregion
        }
Пример #17
0
    private static void BuildAllAssetBundles(string outputPath)
    {
        // Check Output Directory
        string targetFolderName = EditorUserBuildSettings.activeBuildTarget.ToString ();
        string properPath = Path.Combine (outputPath, targetFolderName);
        if (FileUtility.CreateDirectory (properPath) == false)
        {
            Debug.LogErrorFormat ("Output Directory Error path={0}", properPath);
            return;
        }

        // Check Source Directory
        string sourceDirectory = ResourceManagerSettings.AssetBundleSourceDirectory;
        if (Directory.Exists (sourceDirectory) == false)
        {
            Debug.LogErrorFormat ("Source Directory Error path={0}", sourceDirectory);
            return;
        }

        // Create Build Asset List
        List<AssetBundleBuild> listAssetBunle = new List<AssetBundleBuild> ();
        foreach (var assetName in AssetDatabase.GetAllAssetPaths ())
        {
            if (assetName.StartsWith (sourceDirectory) == false)
                continue;
            if (assetName.EndsWith (".cs") == true || assetName.EndsWith (".js") == true || assetName.EndsWith (".boo") == true)
                continue;
            if (AssetDatabase.IsValidFolder (assetName) == true)
                continue;

            string assetBundleName = assetName.Substring (sourceDirectory.Length, assetName.LastIndexOf ('.') - sourceDirectory.Length);
            AssetBundleBuild build = new AssetBundleBuild ();
            build.assetBundleName = assetBundleName;
            build.assetNames = new string[] { assetName };

            listAssetBunle.Add (build);
            Debug.LogFormat ("Build Asset : {0}", assetBundleName);
        }

        // Create AssetBundles
        AssetBundleManifest manifest = BuildPipeline.BuildAssetBundles (
            properPath,
            listAssetBunle.ToArray (),
            BuildAssetBundleOptions.None,
            EditorUserBuildSettings.activeBuildTarget
        );
        Debug.Log ("Build AssetBundle Complete");

        // Create CRC File
        Dictionary<string, uint> dictCRC = new Dictionary<string, uint> ();
        foreach (var assetBundle in manifest.GetAllAssetBundles ())
        {
            uint crc = 0;
            if (BuildPipeline.GetCRCForAssetBundle (Path.Combine (properPath, assetBundle), out crc))
            {
                dictCRC.Add (assetBundle, crc);
                Debug.LogFormat ("CRC : {0} {1}", crc, assetBundle);
            }
        }

        string json = JsonMapper.ToJson (dictCRC);
        using (StreamWriter stream = File.CreateText (Path.Combine (properPath, ResourceManagerSettings.CRCFileName)))
        {
            stream.Write (json);
            stream.Close ();
        }
        Debug.Log ("Created CRD Json Complete");
    }
Пример #18
0
    private void BuildAssetBundle(BuildTarget Target, string Ext)
    {
        EffectDiscriptor effectDiscriptor = (EffectDiscriptor)serializedObject.targetObject;
        string           name             = Regex.Replace(effectDiscriptor.EffectName, @"\s+", "");

        if (autoGrabCover)
        {
            effectDiscriptor.coverImage = getTexture2D(screenshotCamera, 1024, 1024);
        }
        GameObject prefab = new GameObject("Effect");

        Selection.activeGameObject.transform.SetParent(prefab.transform);
        PrefabUtility.SaveAsPrefabAsset(prefab, "Assets/Effect.prefab");

        TextAsset effectJson = new TextAsset(JsonUtility.ToJson(effectDiscriptor.GetJSON(), true));

        AssetDatabase.CreateAsset(effectJson, "Assets/effectJson.asset");
        string coverPath = Path.Combine(Application.dataPath, "Covers", name + "Cover.png");

        if (!Directory.Exists(Path.GetDirectoryName(coverPath)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(coverPath));
        }
        File.WriteAllBytes(coverPath, effectDiscriptor.coverImage.EncodeToPNG());

        AssetDatabase.CreateAsset(effectDiscriptor.coverImage, "Assets/Covers/" + name + "Cover.asset");

        AssetBundleBuild assetBundleBuild = default;

        assetBundleBuild.assetNames = new string[]
        {
            "Assets/Effect.prefab",
            "Assets/effectJson.asset",
            "Assets/Covers/" + name + "Cover.asset",
        };
        string path = Path.Combine(Application.dataPath, "EffectResult", effectDiscriptor.EffectName + Ext);

        if (!Directory.Exists(Path.GetDirectoryName(path)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(path));
        }
        //if (string.IsNullOrEmpty(path)) return;
        assetBundleBuild.assetBundleName = Path.GetFileName(path);
        if (File.Exists(path))
        {
            File.Delete(path);
        }
        BuildPipeline.BuildAssetBundles(Path.GetDirectoryName(path), new AssetBundleBuild[] { assetBundleBuild }, 0, Target);
        EditorPrefs.SetString("currentBuildingAssetBundlePath", Path.GetDirectoryName(path));
        //Cleanup

        AssetDatabase.DeleteAsset("Assets/Effect.prefab");
        AssetDatabase.DeleteAsset("Assets/effectJson.asset");
        AssetDatabase.DeleteAsset("Assets/Covers/" + name + "Cover.asset");


        if (CopyToBeatSaberFolder)
        {
            if (!Directory.Exists(Path.Combine(Prefs.BeatSaberPath, "UserData", "Weather", "Effects")))
            {
                Directory.CreateDirectory(Path.Combine(Prefs.BeatSaberPath, "UserData", "Weather", "Effects"));
            }
            string copyPath = Path.Combine(Prefs.BeatSaberPath, "UserData", "Weather", "Effects", effectDiscriptor.EffectName + Ext);
            if (File.Exists(copyPath))
            {
                File.Delete(copyPath);
            }
            File.Copy(path, copyPath);
        }
        effectDiscriptor.transform.parent = null;
        DestroyImmediate(prefab);
        DeleteDirectory(Path.GetDirectoryName(path));
        File.Delete(Path.GetDirectoryName(path) + ".meta");
        AssetDatabase.Refresh();
    }
Пример #19
0
        /// <summary>
        /// 得到一个目录的ABB
        /// </summary>
        private AssetBundleBuild[] GetOneDir()
        {
            DirectoryInfo rDirInfo = new DirectoryInfo(bundleInfo.assetPath);
            if (!rDirInfo.Exists) return null;

            AssetBundleBuild rABB = new AssetBundleBuild();
            rABB.assetBundleName = bundleInfo.name;
            rABB.assetNames = new string[] { bundleInfo.assetPath };
            rABB.assetBundleVariant = Global.BundleExtName;
            return new AssetBundleBuild[] { rABB };
        }
        public static void Effect(RuntimePlatform platform, BuildTarget buildTarget)
        {
            string resRoot = "Assets/Game/Res/";

            List <string> prefabList = new List <string>();

            FindPrefab(resRoot + "effect3d", prefabList);
            FindPrefab(resRoot + "effect_ui", prefabList);

            string[]      filterDirList = new string[] { "Assets/Game/Resources/Image", "Assets/Game/Res/Image" };
            List <string> filterExts    = new List <string>(new string[] { ".cs", ".js", ".TTF" });
            List <string> imageExts     = new List <string>(new string[] { ".jpg", ".png", ".tga", ".psd" });

            Dictionary <string, List <string> > packerDict = new Dictionary <string, List <string> >();
            List <string> otherList = new List <string>();

            string[] dependencies = AssetDatabase.GetDependencies(prefabList.ToArray());
            for (int i = 0; i < dependencies.Length; i++)
            {
                string item = dependencies[i];
                if (prefabList.IndexOf(item) == -1)
                {
                    bool isFilterDir = false;
                    // filter dir
                    foreach (string filterDir in filterDirList)
                    {
                        if (item.IndexOf(filterDir) != -1)
                        {
                            isFilterDir = true;
                            break;
                        }
                    }

                    if (isFilterDir)
                    {
                        continue;
                    }


                    string ext = Path.GetExtension(item);
                    if (filterExts.IndexOf(ext) == -1)
                    {
                        if (imageExts.IndexOf(ext) != -1)
                        {
                            TextureImporter importer = TextureImporter.GetAtPath(item) as TextureImporter;
                            if (importer.textureType == TextureImporterType.Sprite && !string.IsNullOrEmpty(importer.spritePackingTag))
                            {
                                List <string> list = new List <string>();
                                if (!packerDict.TryGetValue(importer.spritePackingTag, out list))
                                {
                                    list = new List <string>();
                                    packerDict.Add(importer.spritePackingTag, list);
                                }
                                list.Add(item);
                            }
                            else
                            {
                                otherList.Add(item);
                            }
                        }
                        else
                        {
                            otherList.Add(item);
                        }
                    }
                }
            }



            AssetBundleBuild[] builds = new AssetBundleBuild[prefabList.Count + otherList.Count + packerDict.Count];
            int index = 0;

            for (int i = 0; i < prefabList.Count; i++)
            {
                builds[index] = new AssetBundleBuild();

                string assetBundleName = prefabList[i].Replace(resRoot, "").ToLower();
                assetBundleName = PathUtil.ChangeExtension(assetBundleName, EXT);
                builds[index].assetBundleName = assetBundleName;
                builds[index].assetNames      = new string[] { prefabList[i] };
                index++;
            }

            for (int i = 0; i < otherList.Count; i++)
            {
                builds[index] = new AssetBundleBuild();
                string assetBundleName = otherList[i].Replace(resRoot, "").ToLower();
                assetBundleName = PathUtil.ChangeExtension(assetBundleName, EXT);
                builds[index].assetBundleName = assetBundleName;
                builds[index].assetNames      = new string[] { otherList[i] };
                index++;
            }


            foreach (KeyValuePair <string, List <string> > kvp in  packerDict)
            {
                builds[index] = new AssetBundleBuild();
                string assetBundleName = kvp.Key.ToLower();
                assetBundleName = PathUtil.ChangeExtension(assetBundleName, EXT);
                builds[index].assetBundleName = assetBundleName;
                builds[index].assetNames      = kvp.Value.ToArray();
                index++;
            }



            string outPath      = GetOutRoot(platform, isStreamAssetsPath);
            string manifestName = Path.GetDirectoryName(outPath);

            manifestName = manifestName.Substring(manifestName.LastIndexOf("/") + 1).ToLower();

            PathUtil.CheckPath(outPath, false);
            BuildPipeline.BuildAssetBundles(outPath, builds, BuildAssetBundleOptions.None, buildTarget);


            File.Copy(outPath + manifestName, outPath + "effect", true);
            File.Copy(outPath + manifestName + ".manifest", outPath + "effect.manifest", true);
            File.Delete(outPath + manifestName);
            File.Delete(outPath + manifestName + ".manifest");

            AssetDatabase.Refresh();
        }
Пример #21
0
    public static void BuildAssetBundle()
    {
        singlePathSet.Clear();
        bundleDic.Clear();
        //查找所有一级资源(以及需要被代码直接加载的资源)
        //这里建议所有需要单独加载的资源放在统一的文件夹内,要不容易落下
        //这个模块没有放在外部,而写在代码里,主要是考虑很多路径是变量,放在外部不好管理
        string[] strings = AssetDatabase.FindAssets("t:prefab t:scene t:AudioClip", new string[] { "Assets" });
        for (int i = 0, count = strings.Length; i < count; i++)
        {
            singlePathSet.Add(AssetDatabase.GUIDToAssetPath(strings[i]));
        }
        //所有数据打包
        strings = AssetDatabase.FindAssets("", new string[] { "Assets/Resources/Data" });
        for (int i = 0, count = strings.Length; i < count; i++)
        {
            singlePathSet.Add(AssetDatabase.GUIDToAssetPath(strings[i]));
        }
        //反射资源路径类(因为在这个类里的一定都是需要单独加载的),遍历所有路径进行添加,由于set添加重复元素不会报错,所以这里不用处理
        FieldInfo[] fieldInfos = typeof(ResPath).GetFields();
        for (int i = 0; i < fieldInfos.Length; i++)
        {
            singlePathSet.Add(fieldInfos[i].GetValue(null).ToString());
        }
        //在这里添加单独引用的资源

        foreach (var item in singlePathSet)
        {
            bundleDic.Add(item, item);
        }
        foreach (var item in singlePathSet)
        {
            CheckDepends(item, item);
        }
        //转为打包格式
        Dictionary <string, List <string> > dependsDic = new Dictionary <string, List <string> >();

        foreach (var kv in bundleDic)
        {
            string singlePath = kv.Value;
            //场景特殊处理,场景不能和其他东西在一个Bundle里
            if (singlePath.EndsWith(".unity"))
            {
                singlePath = kv.Key;
            }
            if (!dependsDic.ContainsKey(singlePath))
            {
                dependsDic.Add(singlePath, new List <string>());
            }
            dependsDic[singlePath].Add(kv.Key);
        }

        //最终打包List
        List <AssetBundleBuild> buildList = new List <AssetBundleBuild>();

        foreach (var kv in dependsDic)
        {
            AssetBundleBuild build = new AssetBundleBuild();
            build.assetBundleName = AssetBundleLoad.GetAbName(kv.Key);
            build.assetNames      = kv.Value.ToArray();
            buildList.Add(build);
        }

        string path = AssetBundleLoad.GetAbPath();

        //这里得创建下文件夹,他不会帮你创建
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        BuildPipeline.BuildAssetBundles(path, buildList.ToArray(), BuildAssetBundleOptions.UncompressedAssetBundle, EditorUserBuildSettings.activeBuildTarget);
        //删除多余资源
        DeleteUnUsefulAssetBundle();

        //把新hash变成老的
        string newHashPath = GetNewHashPath();

        if (File.Exists(newHashPath))
        {
            FileTools.Copy(newHashPath, GetOldHashPath());
        }
        //写入最新hash
        FileTools.WriteAllText(GetNewHashPath(), JsonMapper.ToJson(GetAllAssetbundleHashList()));
        Debug.Log("打包完成");
    }
Пример #22
0
        public static void ExportAvatarBundle()
        {
            GameObject obj = Selection.activeGameObject;
            string     error;

            if (!AvatarCheck.CheckAvatar(obj, out error))
            {
                EditorUtility.DisplayDialog("Export Avatar Bundle", error, "OK");
                return;
            }

            string fullpath = EditorUtility.SaveFilePanel("Export Avatar Bundle", ".", obj.name, "vsfavatar");

            if (fullpath == null || fullpath == "")
            {
                return;
            }

            string filename = Path.GetFileName(fullpath);

            bool   complete   = false;
            string prefabPath = "Assets/VSFAvatarTemporary.prefab";

            try {
                AssetDatabase.DeleteAsset(prefabPath);
                if (File.Exists(prefabPath))
                {
                    File.Delete(prefabPath);
                }

                bool succeededPack = false;
                PrefabUtility.SaveAsPrefabAsset(obj, prefabPath, out succeededPack);
                if (!succeededPack)
                {
                    Debug.Log("Prefab creation failed");
                    return;
                }

                AssetBundleBuild bundleBuild = new AssetBundleBuild();
                AssetDatabase.RemoveUnusedAssetBundleNames();
                bundleBuild.assetBundleName  = filename;
                bundleBuild.assetNames       = new string[] { prefabPath };
                bundleBuild.addressableNames = new string[] { "VSFAvatar" };

                BuildAssetBundleOptions options = BuildAssetBundleOptions.ForceRebuildAssetBundle | BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.StrictMode;
                if (obj.GetComponentsInChildren <UnityEngine.Video.VideoPlayer>(true).Length > 0)
                {
                    Debug.Log("VideoPlayer detected, using uncompressed asset bundle.");
                    options = options | BuildAssetBundleOptions.UncompressedAssetBundle;
                }
                BuildPipeline.BuildAssetBundles(Application.temporaryCachePath, new AssetBundleBuild[] { bundleBuild }, options, BuildTarget.StandaloneWindows);
                if (File.Exists(fullpath))
                {
                    File.Delete(fullpath);
                }
                File.Move(Application.temporaryCachePath + "/" + filename, fullpath);

                EditorUtility.DisplayDialog("Export", "Export complete!", "OK");
                complete = true;
            }
            finally
            {
                try {
                    AssetDatabase.DeleteAsset(prefabPath);
                    if (File.Exists(prefabPath))
                    {
                        File.Delete(prefabPath);
                    }
                } catch {}

                if (!complete)
                {
                    EditorUtility.DisplayDialog("Export", "Export failed! See the console for details.", "OK");
                }
            }
        }
Пример #23
0
        /// <summary>
        /// 添加 assetbundleBuild
        /// </summary>
        /// <param name="dirName">目录</param>
        /// <param name="files">子文件</param>
        static void AddAssetMap(string dirName, string[] files)
        {
            List <string> abFiles = new List <string>();

            for (int i = 0; i < files.Length; i++)
            {
                string item = files[i];

                //忽略不打包文件
                if (!CanPack(item))
                {
                    Debug.Log("过滤: " + item);
                    continue;
                }

                item = item.Replace('\\', '/');

                //获取相对路径
                item = PathHelper.GetRelativeProjectPath(item);
                abFiles.Add(item);
            }

            if (abFiles.Count == 0)
            {
                return;
            }

            AssetDatabase.Refresh();

            string[]         tempNames;
            string           abName;
            AssetBundleBuild ab = new AssetBundleBuild();


            if (Directory.GetDirectories(dirName).Length != 0)
            {
                //目录下有文件夹时,目录下的子文件一个一个地打包
                dirName = PathHelper.GetRelativeResPath(dirName);
                for (int j = 0; j < abFiles.Count; j++)
                {
                    tempNames = abFiles[j].Split('/');
                    abName    = tempNames[tempNames.Length - 1];
                    if (string.IsNullOrEmpty(dirName))
                    {
                        ab.assetBundleName = abName.Split('.')[0];
                    }
                    else
                    {
                        ab.assetBundleName = dirName + "/" + abName.Split('.')[0];
                    }
                    ab.assetNames = new string[] { abFiles[j] };
                    map.Add(ab);
                }
            }
            else
            {
                //否则,目录下所有子文件打包成一个
                tempNames          = dirName.Split(new string[] { PathHelper.ResPath + "/" }, StringSplitOptions.RemoveEmptyEntries);
                abName             = tempNames[tempNames.Length - 1];
                ab.assetBundleName = abName;
                ab.assetNames      = abFiles.ToArray();
                map.Add(ab);
            }
        }
Пример #24
0
 protected virtual bool IsOverrideBuild(string trackingFile, AssetBundleBuild buildInfo)
 {
     return(false);
 }
Пример #25
0
    //-------------------------------------------------------------------------
    void _packAssetBundleCompress()
    {
        EditorUserBuildSettings.SwitchActiveBuildTarget(mCurrentBuildTarget);

        _getCurrentTargetPath();
        _checkPatchData();

        _deleteFile(mTargetPlatformRootPath);

        Caching.CleanCache();

        _getAllFiles(mAssetBundleResourcesPath);

        if (!Directory.Exists(mTargetPath))
        {
            Directory.CreateDirectory(mTargetPath);
        }

        foreach (var obj in mListAllABFile)
        {
            if (File.Exists(obj))
            {
                string path = Path.GetFullPath(obj);
                path = path.Replace(@"\", "/");
                path = path.Replace(mAssetPath, "");
                path = mTargetPath + "/" + path;
                string obj_dir = path.Replace(Path.GetFileName(obj), "");
                if (!Directory.Exists(obj_dir))
                {
                    Directory.CreateDirectory(obj_dir);
                }
                var names = AssetDatabase.GetDependencies(obj);

                AssetBundleBuild abb;
                abb.assetBundleName = Path.GetFileNameWithoutExtension(obj) + ".ab";
                abb.assetBundleVariant = "";
                int asset_index = 0;
                List<string> list_needbuildassetname = new List<string>();
                //list_needbuildassetname.Add(obj.Replace(mAssetPath, "Assets/"));
                foreach (var j in names)
                {
                    //Debug.Log("Asset: " + j);
                    if (j.EndsWith(".cs") || j.EndsWith(".ttf")) continue;
                    if (list_needbuildassetname.Contains(j))
                    {
                        continue;
                    }
                    list_needbuildassetname.Add(j);
                }
                abb.assetNames = new string[list_needbuildassetname.Count];

                foreach (var i in list_needbuildassetname)
                {
                    abb.assetNames[asset_index++] = i;
                }

                AssetBundleBuild[] arr_abb = new AssetBundleBuild[1];
                arr_abb[0] = abb;

                _buildAssetBundleCompressed(arr_abb, obj_dir, mCurrentBuildTarget, false);
                //#if UNITY_STANDALONE_WIN
                //                _buildAssetBundleCompressed(arr_abb, obj_dir, BuildTarget.StandaloneWindows64, false);
                //#elif UNITY_IOS||UNITY_IPHONE
                //                _buildAssetBundleCompressed(arr_abb, obj_dir, BuildTarget.iOS, false);
                //#elif UNITY_ANDROID
                //                _buildAssetBundleCompressed(arr_abb, obj_dir, BuildTarget.Android, false);
                //#endif
            }
        }

        if (Directory.Exists(mRowAssetPath))
        {
            copyFile(mRowAssetPath, mTargetPath, "Assets/");
        }

        Debug.Log("裸资源复制完毕!");

        _packResources(mTargetPath);
    }
Пример #26
0
        /// <summary>
        /// 打包(生成)场景和 AssetBundle 资源
        /// </summary>
        private static void GenerateAssets()
        {
            string targetPlatform = GetCmdLineArg("-targetPlatform");
            string manifestPath   = GetCmdLineArg("-manifestPath");
            string outputDir      = GetCmdLineArg("-outputDir");
            string scenes         = GetCmdLineArg("-scenes");
            string outFilePath    = GetCmdLineArg("-logFile").Replace("unity.log", "unity.out");

            //string targetPlatform = "android";
            //string manifestPath = "/Users/limylee/LOLO/unity/projects/ShibaInu/Tools/build/log/0/manifest.log";
            //string outputDir = "/Users/limylee/LOLO/unity/projects/ShibaInu/Tools/build/ShibaInu/cache/";
            //string scenes = "2,3";
            //string outFilePath = "/Users/limylee/LOLO/unity/projects/ShibaInu/Tools/build/log/0/unity.out";

            // 需要打包的场景索引列表
            string[] buildScenes = scenes.Split(',');

            // 目标平台
            BuildTarget buildTarget = default;

            switch (targetPlatform)
            {
            case "ios":
                buildTarget = BuildTarget.iOS;
                break;

            case "android":
                buildTarget = BuildTarget.Android;
                break;

            case "macos":
                buildTarget = BuildTarget.StandaloneOSX;
                break;

            case "windows":
                buildTarget = BuildTarget.StandaloneWindows;
                break;
            }

            // 解析打包清单
            List <string>           sceneList = new List <string>();
            List <AssetBundleBuild> abbList   = new List <AssetBundleBuild>();

            using (StreamReader file = new StreamReader(manifestPath))
            {
                string           line;
                int              phase = 1, index = 0, count = 0;
                AssetBundleBuild abb    = default;
                List <string>    assets = new List <string>();
                while ((line = file.ReadLine()) != null)
                {
                    switch (phase)
                    {
                    // lua
                    case 1:
                        if (count == 0)
                        {
                            count = int.Parse(line);
                        }
                        else
                        {
                            if (++index == count)
                            {
                                count = index = 0;
                                phase++;
                            }
                        }
                        break;

                    // scene
                    case 2:
                        if (count == 0)
                        {
                            count = int.Parse(line);
                        }
                        else
                        {
                            sceneList.Add(line);
                            if (++index == count)
                            {
                                count = index = 0;
                                phase++;
                            }
                        }
                        break;

                    // AssetBundle
                    case 3:
                        if (count == 0)
                        {
                            count = int.Parse(line);
                        }
                        else
                        {
                            if (index == 0)
                            {
                                abb = new AssetBundleBuild {
                                    assetBundleName = line
                                };
                                assets.Clear();
                            }
                            else
                            {
                                assets.Add(line);
                            }

                            if (++index == count)
                            {
                                count          = index = 0;
                                abb.assetNames = assets.ToArray();
                                abbList.Add(abb);
                            }
                        }
                        break;
                    }
                }
            }


            // 打包场景
            if (buildScenes.Length > 0 && buildScenes[0] != "")
            {
                DateTime timeScene = DateTime.Now;
                WriteOut(outFilePath, "build scene start");
                string outputScene = outputDir + "scene/" + targetPlatform + "/";
                if (!Directory.Exists(outputScene))
                {
                    Directory.CreateDirectory(outputScene);
                }
                foreach (string index in buildScenes)
                {
                    DateTime    time       = DateTime.Now;
                    string      scene      = sceneList[int.Parse(index)];
                    string[]    levels     = { scene };
                    string      outputPath = outputScene + Path.GetFileName(scene);
                    BuildReport report     = BuildPipeline.BuildPlayer(levels, outputPath, buildTarget, BuildOptions.BuildAdditionalStreamedScenes);
                    if (report.summary.result == BuildResult.Succeeded)
                    {
                        WriteOut(outFilePath, "build scene complete," + scene + "," + DateTime.Now.Subtract(time).TotalMilliseconds);
                    }
                    else
                    {
                        WriteOut(outFilePath, "build scene error," + scene + "," + report.summary.result);
                        EditorApplication.Exit(1);
                        return;
                    }
                }
                WriteOut(outFilePath, "build scene all complete," + DateTime.Now.Subtract(timeScene).TotalMilliseconds);
            }


            // 打包 AssetBundle
            DateTime timeAB = DateTime.Now;

            WriteOut(outFilePath, "build assetbundle start");
            string outputAB = outputDir + "assetbundle/" + targetPlatform + "/";

            if (!Directory.Exists(outputAB))
            {
                Directory.CreateDirectory(outputAB);
            }
            BuildPipeline.BuildAssetBundles(outputAB, abbList.ToArray(),
                                            BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.ChunkBasedCompression,
                                            buildTarget
                                            );
            WriteOut(outFilePath, "build assetbundle complete," + DateTime.Now.Subtract(timeAB).TotalMilliseconds);


            // 写入 AssetBundle 依赖信息文件
            string              dependenciesFilePath = outputDir + "dependencies.json";
            AssetBundle         ab       = AssetBundle.LoadFromFile(outputAB + targetPlatform);
            AssetBundleManifest manifest = (AssetBundleManifest)ab.LoadAsset("AssetBundleManifest");

            string[] abList = manifest.GetAllAssetBundles();
            using (StreamWriter writer = new StreamWriter(File.Open(dependenciesFilePath, FileMode.Create)))
            {
                writer.Write("{");
                bool isFirst = true;
                foreach (string abPath in abList)
                {
                    string[] depList = manifest.GetAllDependencies(abPath);
                    if (depList.Length > 0)
                    {
                        if (isFirst)
                        {
                            isFirst = false;
                        }
                        else
                        {
                            writer.Write(",");
                        }
                        writer.Write("\n  \"" + abPath + "\": [");
                        for (int i = 0; i < depList.Length; i++)
                        {
                            if (i != 0)
                            {
                                writer.Write(", ");
                            }
                            writer.Write("\"" + depList[i].Replace("\\", "/") + "\"");
                        }
                        writer.Write("]");
                    }
                }
                writer.Write("\n}");
            }

            //
        }
Пример #27
0
    static private List <AssetBundleBuild> BuildUnitAssetBundles(BuildAssetBundleOptions opt,
                                                                 BuildTarget biuldTarget,
                                                                 Dictionary <string, AssetBundleInfo> assetInfoDict,
                                                                 string outputPath)
    {
        Debug.Log("處理資源: Unit");

        //讀取UnitConfig配置文件,只有這個文件配置的Unit才會記錄在reslist.json裡

        string      text   = File.ReadAllText(string.Format("{0}/Config/UnitConfig.xml", ASSET_BUNDLE_SRC_DIR));
        XMLInStream stream = new XMLInStream(text);

        Dictionary <string, UnitConfig> UnitConfigs = new Dictionary <string, UnitConfig>();

        stream.List("item", delegate(XMLInStream itemStream)
        {
            UnitConfig ufg = new UnitConfig(itemStream);

            //注意這裡用的是ResourceIcon字段
            if (!UnitConfigs.ContainsKey(ufg.ResourceIcon))
            {
                UnitConfigs.Add(ufg.ResourceIcon, ufg);
            }
        });

        List <AssetBundleBuild> ret = new List <AssetBundleBuild>();

        //生成prefab的AssetBundle
        foreach (var pair in UnitConfigs)
        {
            DirectoryInfo dInfo = new DirectoryInfo(string.Format("{0}/Unit/{1}", ASSET_BUNDLE_SRC_DIR, pair.Key));

            //這裡注意轉成小寫
            string assetbundlename = "unit/" + pair.Key.ToLower();
            if (!dInfo.Exists)
            {
                // 如果UnitConfig配置裡沒有的字段,需要從reslist.json裡清理掉
                if (assetInfoDict.ContainsKey(assetbundlename))
                {
                    assetInfoDict.Remove(assetbundlename);
                }
                continue;
            }

            AssetBundleBuild abb = new AssetBundleBuild();
            abb.assetBundleName = assetbundlename;
            string[] assetNames = { string.Format("{0}/Unit/{1}/{2}.prefab", ASSET_BUNDLE_SRC_DIR, pair.Key, pair.Key) };
            abb.assetNames = assetNames;
            ret.Add(abb);
        }

        //生成UnitImg的AssetBundle
        foreach (var pair in UnitConfigs)
        {
            //夥伴圖1
            string p1 = string.Format("{0}/UnitImg1/{1}.png", ASSET_BUNDLE_SRC_DIR, pair.Key);
            //夥伴圖2
            string   p2              = string.Format("{0}/UnitImg2/{1}.png", ASSET_BUNDLE_SRC_DIR, pair.Key);
            FileInfo img1Info        = new FileInfo(p1);
            FileInfo img2Info        = new FileInfo(p2);
            string   assetbundlename = string.Format("unitimg/{0}img", pair.Key.ToLower());
            if (!img1Info.Exists && !img2Info.Exists)
            {
                continue;
            }

            AssetBundleBuild abb = new AssetBundleBuild();
            abb.assetBundleName = assetbundlename;
            string[] assetNames = { p1, p2 };
            abb.assetNames = assetNames;
            ret.Add(abb);
        }

        return(ret);
    }
Пример #28
0
    //-------------------------------------------------------------------------
    void _packAssetBundleCompress()
    {
        EditorUserBuildSettings.SwitchActiveBuildTarget(mCurrentBuildTarget);

        _getCurrentTargetPath();
        _checkPatchData();

        _deleteFile(mTargetPlatformRootPath);

        Caching.CleanCache();

        _getAllFiles(mAssetBundleResourcesPath);

        if (!Directory.Exists(mTargetPath))
        {
            Directory.CreateDirectory(mTargetPath);
        }

        foreach (var obj in mListAllABFile)
        {
            if (File.Exists(obj))
            {
                string path = Path.GetFullPath(obj);
                path = path.Replace(@"\", "/");
                path = path.Replace(mAssetPath, "");
                path = mTargetPath + "/" + path;
                string obj_dir = path.Replace(Path.GetFileName(obj), "");
                if (!Directory.Exists(obj_dir))
                {
                    Directory.CreateDirectory(obj_dir);
                }
                var names = AssetDatabase.GetDependencies(obj);

                AssetBundleBuild abb;
                abb.assetBundleName    = Path.GetFileNameWithoutExtension(obj) + ".ab";
                abb.assetBundleVariant = "";
                int           asset_index             = 0;
                List <string> list_needbuildassetname = new List <string>();
                //list_needbuildassetname.Add(obj.Replace(mAssetPath, "Assets/"));
                foreach (var j in names)
                {
                    //Debug.Log("Asset: " + j);
                    if (j.EndsWith(".cs") || j.EndsWith(".ttf"))
                    {
                        continue;
                    }
                    if (list_needbuildassetname.Contains(j))
                    {
                        continue;
                    }
                    list_needbuildassetname.Add(j);
                }
                abb.assetNames = new string[list_needbuildassetname.Count];

                foreach (var i in list_needbuildassetname)
                {
                    abb.assetNames[asset_index++] = i;
                }

                AssetBundleBuild[] arr_abb = new AssetBundleBuild[1];
                arr_abb[0] = abb;

                _buildAssetBundleCompressed(arr_abb, obj_dir, mCurrentBuildTarget, false);
                //#if UNITY_STANDALONE_WIN
                //                _buildAssetBundleCompressed(arr_abb, obj_dir, BuildTarget.StandaloneWindows64, false);
                //#elif UNITY_IOS||UNITY_IPHONE
                //                _buildAssetBundleCompressed(arr_abb, obj_dir, BuildTarget.iOS, false);
                //#elif UNITY_ANDROID
                //                _buildAssetBundleCompressed(arr_abb, obj_dir, BuildTarget.Android, false);
                //#endif
            }
        }

        if (Directory.Exists(mRowAssetPath))
        {
            copyFile(mRowAssetPath, mTargetPath, "Assets/");
        }

        Debug.Log("裸资源复制完毕!");

        _packResources(mTargetPath);
    }
Пример #29
0
        /// <summary>
        /// 得到一个目录下的所有的文件对应的ABB
        /// </summary>
        private AssetBundleBuild[] GetOneDir_Files()
        {
            DirectoryInfo rDirInfo = new DirectoryInfo(bundleInfo.assetPath);
            if (!rDirInfo.Exists) return null;

            List<string> allABPaths = new List<string>();
            Util.RecursiveDir(bundleInfo.assetPath, ref allABPaths);

            List<AssetBundleBuild> rABBList = new List<AssetBundleBuild>();

            for (int i = 0; i < allABPaths.Count; i++)
            {
                string rAssetPath = allABPaths[i];
                AssetBundleBuild rABB = new AssetBundleBuild();
                rABB.assetBundleName = bundleInfo.name + "/" + Path.GetFileNameWithoutExtension(rAssetPath);
                rABB.assetNames = new string[] { rAssetPath };
                rABB.assetBundleVariant = Global.BundleExtName;
                rABBList.Add(rABB);
            }

            return rABBList.ToArray();
        }
Пример #30
0
        /// <inheritdoc />
        protected override string ProcessGroup(AddressableAssetGroup assetGroup, AddressableAssetsBuildContext aaContext)
        {
            var errorString = string.Empty;
            PlayerDataGroupSchema playerSchema = assetGroup.GetSchema <PlayerDataGroupSchema>();

            if (playerSchema != null)
            {
                if (CreateLocationsForPlayerData(playerSchema, assetGroup, aaContext.locations))
                {
                    if (!m_CreatedProviderIds.ContainsKey(typeof(LegacyResourcesProvider).Name))
                    {
                        m_CreatedProviderIds.Add(typeof(LegacyResourcesProvider).Name, null);
                        m_ResourceProviderData.Add(ObjectInitializationData.CreateSerializedInitializationData(typeof(LegacyResourcesProvider)));
                    }
                }
                return(errorString);
            }

            var schema = assetGroup.GetSchema <BundledAssetGroupSchema>();

            if (schema == null)
            {
                return(errorString);
            }

            var bundledProviderId = schema.GetBundleCachedProviderId();
            var assetProviderId   = schema.GetAssetCachedProviderId();

            if (!m_CreatedProviderIds.ContainsKey(bundledProviderId))
            {
                //TODO: pull from schema instead of ProjectConfigData
                var virtualBundleRuntimeData = new VirtualAssetBundleRuntimeData(ProjectConfigData.localLoadSpeed, ProjectConfigData.remoteLoadSpeed);
                //save virtual runtime data to collect assets into virtual bundles
                m_CreatedProviderIds.Add(bundledProviderId, virtualBundleRuntimeData);
            }

            if (!m_CreatedProviderIds.ContainsKey(assetProviderId))
            {
                m_CreatedProviderIds.Add(assetProviderId, null);

                var assetProviderData = ObjectInitializationData.CreateSerializedInitializationData <VirtualBundledAssetProvider>(assetProviderId);
                m_ResourceProviderData.Add(assetProviderData);
            }


            var bundleInputDefs = new List <AssetBundleBuild>();

            PrepGroupBundlePacking(assetGroup, bundleInputDefs, schema.BundleMode);
            for (int i = 0; i < bundleInputDefs.Count; i++)
            {
                if (aaContext.bundleToAssetGroup.ContainsKey(bundleInputDefs[i].assetBundleName))
                {
                    var bid     = bundleInputDefs[i];
                    int count   = 1;
                    var newName = bid.assetBundleName;
                    while (aaContext.bundleToAssetGroup.ContainsKey(newName) && count < 1000)
                    {
                        newName = bid.assetBundleName.Replace(".bundle", string.Format("{0}.bundle", count++));
                    }
                    bundleInputDefs[i] = new AssetBundleBuild {
                        assetBundleName = newName, addressableNames = bid.addressableNames, assetBundleVariant = bid.assetBundleVariant, assetNames = bid.assetNames
                    };
                }

                aaContext.bundleToAssetGroup.Add(bundleInputDefs[i].assetBundleName, assetGroup.Guid);
            }

            m_AllBundleInputDefinitions.AddRange(bundleInputDefs);

            return(errorString);
        }
Пример #31
0
    static void ExportAvatarResource()
    {
        VRCSDK2.VRC_AvatarDescriptor Desc = ( Selection.activeObject as GameObject ).GetComponent<VRCSDK2.VRC_AvatarDescriptor>();
        if( Desc == null )
        {
            UnityEditor.EditorUtility.DisplayDialog("Build Custom Avatar", "You must place a VRC_AvatarDescriptor on the root of you custom scene", "Ok" );
            return;
        }

        //if( CheckCompatibility( Selection.activeObject as GameObject ) > 0 )
        //{
        //    UnityEditor.EditorUtility.DisplayDialog("Build Custom Avatar", "Your avatar scene contains depricated scripts. See the error log.", "Ok" );
        //    return;
        //}

        PrefabUtility.CreatePrefab( "Assets/_CustomAvatar.prefab", Selection.activeObject as GameObject );
        AssetBundleBuild abb = new AssetBundleBuild();
        abb.assetNames = new string[] {"Assets/_CustomAvatar.prefab"};
        abb.assetBundleName = "customAvatar.unity3d";

        string vrcaPath = EditorUtility.SaveFilePanel ("Save Custom Avatar", "", "NewAvatar", "vrca");
        string tmpAssetBundlePath = Application.temporaryCachePath + "/" + abb.assetBundleName;

        if (vrcaPath.Length != 0)
        {
            BuildTarget InitialTarget = EditorUserBuildSettings.activeBuildTarget;
            BuildPipeline.BuildAssetBundles(Application.temporaryCachePath, new AssetBundleBuild[] { abb }, BuildAssetBundleOptions.UncompressedAssetBundle);
            UnityEngine.Debug.Log("PATH: " + vrcaPath);
            lzma.LzmaUtilEncode(tmpAssetBundlePath, vrcaPath);
            recentlySavedPath = vrcaPath;
            EditorUserBuildSettings.SwitchActiveBuildTarget(InitialTarget);
        }

        AssetDatabase.DeleteAsset("Assets/_CustomAvatar.prefab");
        AssetDatabase.Refresh();

        VRCSDK2.VRC_Editor.RecordActivity("avatar", Path.GetFileName(vrcaPath));
    }
Пример #32
0
 static void AssetBundle_Build()
 {
     AssetBundleBuild.ShowWindow();
 }
Пример #33
0
    static void AddBuildMap(string bundleName, string pattern, string path)
    {
        string[] files = Directory.GetFiles(path, pattern);
        if (files.Length == 0) return;

        for (int i = 0; i < files.Length; i++) {
            files[i] = files[i].Replace('\\', '/');
        }
        AssetBundleBuild build = new AssetBundleBuild();
        build.assetBundleName = bundleName;
        build.assetNames = files;
        maps.Add(build);
    }
Пример #34
0
 static void AssetBundle_BuildAllPlatform()
 {
     AssetBundleBuild.BuildAllPlatform();
 }
Пример #35
0
        /// <summary>
        /// 将文件打入bundle
        /// </summary>
        private static List <AssetBundleBuild> MakeAssetBundleBuild(string _module, string _abname, string[] _files)
        {
            _module = _module.ToLower();
            _abname = _abname.ToLower();

            List <AssetBundleBuild> _bundles = new List <AssetBundleBuild>();
            List <string>           _luas    = new List <string>();
            List <string>           _list    = new List <string>();

            for (int i = 0; i < _files.Length; i++)
            {
                string _oneFile = _files[i].ToLower();
                string _ext     = Path.GetExtension(_oneFile);
                if (FilterExtensions.IndexOf(_ext) != -1)
                {
                    continue;
                }
                string _one = Utility.MakeUnifiedDirectory(_oneFile);
                //改变lua文件格式,assetbundle不识别.lua后缀名
                if (_one.EndsWith(".lua"))
                {
                    string _luaToTxt = _one.Replace(".lua", ".bytes");
                    //写一份lua的临时文件
                    byte[] _rp = File.ReadAllBytes(_one);
                    _rp = Utility.Encrypt(_rp, ProjectDatas.CODEKEY);
                    File.WriteAllBytes(_luaToTxt, _rp);

                    _luas.Add(_luaToTxt);
                }
                //协议文件暂时不做加密
                else if (_one.EndsWith(".pb"))
                {
                    string _luaToTxt = _one.Replace(".pb", ".bytes");
                    //写一份lua的临时文件
                    byte[] _rp = File.ReadAllBytes(_one);
                    File.WriteAllBytes(_luaToTxt, _rp);

                    _luas.Add(_luaToTxt);
                }
                else
                {
                    _list.Add(_one);
                }
            }

            AssetBundleBuild _build;

            if (_list.Count > 0)
            {
                _build = new AssetBundleBuild();
                _build.assetBundleName = (_module + "/" + _abname);;
                _build.assetNames      = _list.ToArray();
                _bundles.Add(_build);
            }

            if (_luas.Count > 0)
            {
                _build = new AssetBundleBuild();
                _build.assetBundleName = (_module + "/" + _abname);;
                _build.assetNames      = _luas.ToArray();
                _bundles.Add(_build);
            }

            return(_bundles);
        }
Пример #36
0
        protected List <AssetBundleBuild> collectionPrefab(string prefabPath)
        {
            string[]      depends   = AssetDatabase.GetDependencies(new string[] { prefabPath });
            List <string> innerList = new List <string>();

            List <AssetBundleBuild> builds = new List <AssetBundleBuild>();

            foreach (string depend in depends)
            {
                string extension = Path.GetExtension(depend).ToLower();
                switch (extension)
                {
                case ".jpg":
                case ".png":
                    if (depend == prefabPath)
                    {
                        innerList.Add(depend);
                    }
                    else
                    {
                        bitmaps.Add(depend);
                    }
                    break;

                case ".shader":
                    shaders.Add(depend);
                    break;

                case ".dll":
                    break;

                case ".cs":
                    break;

                case ".ttf":
                    ttfs.Add(depend);
                    break;

                case ".mat":
                    materials.Add(depend);
                    break;

                case ".fbx":
                    fbxs.Add(depend);
                    break;

                case ".anim":
                    anims.Add(depend);
                    break;

                case ".controller":
                    controllers.Add(depend);
                    break;

                case ".prefab":
                    if (depend != prefabPath)
                    {
                        prefabs.Add(depend);
                    }
                    else
                    {
                        innerList.Add(depend);
                    }
                    break;

                default:
                    innerList.Add(depend);
                    break;
                }
            }

            AssetBundleBuild build    = new AssetBundleBuild();
            string           fileName = Path.GetFileNameWithoutExtension(prefabPath);

            build.assetBundleName = fileName + ".unity3d";
            build.assetNames      = innerList.ToArray();

            builds.Add(build);

            return(builds);
        }
Пример #37
0
        public override void OverrideBuild(string outpathRoot, List <AssetBundleBuild> filteredBuildInfos)
        {
            for (int i = filteredBuildInfos.Count - 1; i >= 0; --i)
            {
                var buildInfo = filteredBuildInfos[i];
                if (buildInfo.assetBundleName.StartsWith("Assets/" + ResConfig.RES_ROOT + "/" + ResConfig.LUA_ROOT) ||
                    buildInfo.assetBundleName.StartsWith(ResConfig.DEPENDENCIES_ROOT + "/" + ResConfig.RES_ROOT + "/" + ResConfig.LUA_ROOT))
                {
                    filteredBuildInfos.RemoveAt(i);
                }
            }

            var resPath = Application.dataPath + "/" + ResConfig.RES_ROOT + "/" + ResConfig.LUA_ROOT;
            var files   = ResBuildUtility.GetFiles(resPath);

            _tmpFiles.Clear();

            foreach (var file in files)
            {
                if (file.EndsWith(ResConfig.LUA_EXTENSION) == false)
                {
                    continue;
                }

                var sourceFile = file;
                var targetFile = sourceFile.ReplaceLast(ResConfig.LUA_EXTENSION, ResConfig.MOBILE_LUA_EXTENSION);

                if (File.Exists(targetFile))
                {
                    File.Delete(targetFile);
                }
                File.Copy(sourceFile, targetFile);
                _tmpFiles.Add(targetFile);

                var assetBundleName = targetFile.ReplaceFirst(Application.dataPath + "/" + ResConfig.RES_ROOT + "/", "") + ResConfig.BUNDLE_EXTENSION;
                var assetName       = targetFile.ReplaceFirst(_rootPath + "/", "");

                var index = ResBuildUtility.TryGetBuildInfo(filteredBuildInfos, assetBundleName);
                if (index == -1)
                {
                    var buildInfo = new AssetBundleBuild();
                    buildInfo.assetNames      = new string[] { assetName };
                    buildInfo.assetBundleName = assetBundleName;
                    filteredBuildInfos.Add(buildInfo);

                    LogManager.Log("lua assetbundle " + assetBundleName);
                }
                else
                {
                    var buildInfo  = filteredBuildInfos[index];
                    var assetNames = buildInfo.assetNames.ToList();
                    if (assetNames.Contains(assetName))
                    {
                        continue;
                    }

                    assetNames.Add(assetName);
                    buildInfo.assetNames      = assetNames.ToArray();
                    filteredBuildInfos[index] = buildInfo;

                    LogManager.Log("lua assetbundle " + assetBundleName);
                }
            }
            AssetDatabase.Refresh();
        }
Пример #38
0
        public bool exprotPrefabs(List <string> prefabPathList, List <BuildTarget> buildTargets)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(exportPrefabFromPath);
            string        directoryName = directoryInfo.Name;

            int len = prefabPathList.Count;
            List <AssetBundleBuild> builds = new List <AssetBundleBuild>();

            for (int i = 0; i < len; i++)
            {
                List <AssetBundleBuild> tempList = collectionPrefab(prefabPathList[i]);
                if (tempList.Count > 0)
                {
                    builds.AddRange(tempList);
                }
            }

            //内部包含其它的prefab;
            int prefabCount = prefabs.Count;

            while (prefabCount > 0)
            {
                string[] tempPrefabs = prefabs.ToArray();
                prefabs.Clear();

                foreach (string item in tempPrefabs)
                {
                    if (prefabPathList.IndexOf(item) != -1)
                    {
                        continue;
                    }

                    List <AssetBundleBuild> tempList = collectionPrefab(item);
                    if (tempList.Count > 0)
                    {
                        builds.AddRange(tempList);
                    }
                }

                prefabCount = prefabs.Count;
            }

            List <AssetBundleBuild> bitmapBuilds = new List <AssetBundleBuild>();

            foreach (string key in toUnityPathMapping.Keys)
            {
                HashSet <string> itemList = toUnityPathMapping[key];
                foreach (string item in itemList)
                {
                    AssetBundleBuild build           = new AssetBundleBuild();
                    string           fileName        = Path.GetFileNameWithoutExtension(item);
                    string           assetBundleName = directoryName + "_" + key + "/" + fileName + ".unity3d";

                    int hasIndex;
                    if (prefabDirMaping.TryGetValue(assetBundleName, out hasIndex))
                    {
                        prefabDirMaping[assetBundleName] = hasIndex + 1;
                        assetBundleName = directoryName + "_" + key + (hasIndex + 1) + "/" + fileName + ".unity3d";
                    }
                    else
                    {
                        prefabDirMaping.Add(assetBundleName, 0);
                    }

                    build.assetBundleName = assetBundleName;
                    build.assetNames      = new string[] { item };
                    builds.Add(build);
                }
            }

            try
            {
                foreach (BuildTarget buildTarget in buildTargets)
                {
                    string exportPlatformRootPath = Path.Combine(exportPrefabToPath,
                                                                 buildTarget.ToString() + "/" + directoryName);
                    if (Directory.Exists(exportPlatformRootPath) == false)
                    {
                        Directory.CreateDirectory(exportPlatformRootPath);
                    }

                    BuildPipeline.BuildAssetBundles(exportPlatformRootPath, builds.ToArray(),
                                                    BuildAssetBundleOptions.None, buildTarget);
                }
            }
            catch (Exception e)
            {
                Debug.Log("失败:" + e.Message);
                return(false);
            }
            finally
            {
                clearCache();
            }

            return(true);
        }
Пример #39
0
    static void BuildAllAssetBundlesSeparate()
    {
        /*
         * Build an asset bundle for each prefab inside the selected folder of prefabs.
         */
        // Build all bundles existing in the project
        //		BuildPipeline.BuildAssetBundles ("Assets/AssetBundles/", BuildAssetBundleOptions.None, BuildTarget.StandaloneOSXUniversal);
        // For building bundles selectively
        Dictionary<GameObject, string> selectedPrefabs = ListSelectedPrefabs ();
        AssetBundleBuild[] buildMap = new AssetBundleBuild[selectedPrefabs.Count];

        int loop_counter = 0;
        foreach (KeyValuePair<GameObject, string> entry in selectedPrefabs) {
            string _bundleName;
            string[] _assetPath = new string[1];
            _bundleName = entry.Key.name + ".bundle";
            // In case prefabs had some kind of file extension replace the file extension with .bundle
            //			_bundleName = _bundleName.Remove(_bundleName.LastIndexOf('.')) + ".bundle";

            buildMap [loop_counter].assetBundleName = _bundleName;
            _assetPath [0] = entry.Value;
            buildMap [loop_counter].assetNames = _assetPath;
            loop_counter++;
        }

        BuildPipeline.BuildAssetBundles ("Assets/PrefabDatabase/AssetBundles/Separated",
            buildMap,
            BuildAssetBundleOptions.None,
            BuildTarget.StandaloneOSXUniversal
        );
    }
Пример #40
0
    /// <summary>
    /// 打包资源
    /// </summary>
    static void PackBundles()
    {
        //确保目标文件夹存在
        AssetDatabase.Refresh();
        if (!Directory.Exists(bundlesDirePath + "/.Temporary"))
        {
            Directory.CreateDirectory(bundlesDirePath + "/.Temporary");
        }

        //确保db.xml存在
        if (!File.Exists(dbPath + "/db.xml"))
        {
            Directory.Delete(bundlesDirePath + "/.Temporary", true);
            EditorUtility.DisplayDialog("出错啦", "db.xml未找到!", "确定");
            return;
        }
        File.Copy(dbPath + "/db.xml", "Assets/db.xml", true);

        //确保modules.dll存在
        if (!File.Exists(dllPath + "/modules.dll"))
        {
            Directory.Delete(bundlesDirePath + "/.Temporary", true);
            EditorUtility.DisplayDialog("出错啦", "modules.dll未找到!", "确定");
            return;
        }
        File.Copy(dllPath + "/modules.dll", "Assets/modules.bytes", true);

        //确保modules.pdb存在
        if (!File.Exists(dllPath + "/modules.pdb"))
        {
            Directory.Delete(bundlesDirePath + "/.Temporary", true);
            EditorUtility.DisplayDialog("出错啦", "modules.pdb未找到!", "确定");
            return;
        }
        File.Copy(dllPath + "/modules.pdb", "Assets/Code/Freamwork/Editor/Resources/modules.pdb.bytes", true);

        //单独打包db.xml和modules.dll
        AssetDatabase.Refresh();
        AssetBundleBuild[] buildMap = new AssetBundleBuild[2];
        buildMap[0].assetBundleName = "db.assets";
        buildMap[0].assetNames = new string[] { "Assets/db.xml" };
        buildMap[1].assetBundleName = "modules.assets";
        buildMap[1].assetNames = new string[] { "Assets/modules.bytes" };
        BuildPipeline.BuildAssetBundles(bundlesDirePath + "/.Temporary", buildMap,
            BuildAssetBundleOptions.None, BuildTarget.Android);
        File.Copy(bundlesDirePath + "/.Temporary/db.assets", bundlesDirePath + "/db.assets", true);
        File.Copy(bundlesDirePath + "/.Temporary/db.assets.manifest", bundlesDirePath + "/db.assets.manifest", true);
        File.Copy(bundlesDirePath + "/.Temporary/modules.assets", bundlesDirePath + "/modules.assets", true);
        File.Copy(bundlesDirePath + "/.Temporary/modules.assets.manifest", bundlesDirePath + "/modules.assets.manifest", true);
        File.Delete("Assets/db.xml");
        File.Delete("Assets/modules.bytes");

        //打包资源
        AssetDatabase.Refresh();
        BuildPipeline.BuildAssetBundles(bundlesDirePath, BuildAssetBundleOptions.None, BuildTarget.Android);

        //写入manifest.xml
        string xmlStr = "<manifest>" + getXMLStr() + "</manifest>";
        File.WriteAllText(bundlesDirePath + "/manifest.xml", xmlStr);

        //单独打包manifest.xml
        File.Copy(bundlesDirePath + "/manifest.xml", "Assets/manifest.xml", true);
        AssetDatabase.Refresh();
        buildMap = new AssetBundleBuild[1];
        buildMap[0].assetBundleName = "manifest.assets";
        buildMap[0].assetNames = new string[] { "Assets/manifest.xml" };
        BuildPipeline.BuildAssetBundles(bundlesDirePath + "/.Temporary", buildMap,
            BuildAssetBundleOptions.None, BuildTarget.Android);
        File.Copy(bundlesDirePath + "/.Temporary/manifest.assets", bundlesDirePath + "/manifest.assets", true);
        File.Copy(bundlesDirePath + "/.Temporary/manifest.assets.manifest", bundlesDirePath + "/manifest.assets.manifest", true);
        File.Delete("Assets/manifest.xml");

        //打包完成
        Directory.Delete(bundlesDirePath + "/.Temporary", true);
        AssetDatabase.Refresh();
        CopyToCDN();    //拷贝到CDN目录
        EditorUtility.DisplayDialog("提示", "资源打包完毕", "确定");
    }
Пример #41
0
    //-------------------------------------------------------------------------
    static void _buildAssetBundleCompressed(AssetBundleBuild[] arr_abb, string path, BuildTarget target, bool build_all = true)
    {
        if (build_all)
        {
            //BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,
            //  BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, target);
        }
        else
        {
            BuildPipeline.BuildAssetBundles(path, arr_abb, BuildAssetBundleOptions.ForceRebuildAssetBundle, target);
        }

        EbLog.Note("Build AssetBundle BuildTarget=" + target);
    }
Пример #42
0
    public static void CreatePrefabFromModel()
    {
        Dictionary<GameObject, string> allSelected = new Dictionary<GameObject, string> ();

                /*
        foreach (GameObject obj in Selection.gameObjects) {

            allSelected.Add (obj, AssetDatabase.GetAssetPath (obj));

                        tmp_asset_path   = AssetDatabase.GetAssetPath (obj);
                        Debug.Log(tmp_asset_path);
        }

        foreach (UnityEngine.Object obj in Selection.objects) {
            if (obj != null) {
                if (obj is GameObject) {
                    allSelected.Add (obj as GameObject, AssetDatabase.GetAssetPath (obj));

                                        tmp_asset_path   = AssetDatabase.GetAssetPath (obj);
                                        Debug.Log(tmp_asset_path);

                } else if (obj is DefaultAsset) {
                    HashSet<GameObject> children = (obj as DefaultAsset).GetAllChildrenAssets<GameObject> ();
                    foreach (GameObject child in children) {
                        allSelected.Add (child, AssetDatabase.GetAssetPath (child));

                                                tmp_asset_path   = AssetDatabase.GetAssetPath (child);
                                                Debug.Log(tmp_asset_path);
                                                //Debug.Log(AssetDatabase.LoadMainAssetAtPath(tmp_asset_path)==child);
                    }
                }
            }
        }
                */

                //string tmp_asset_path = "Assets/Models/sel_objs/02747177/8acbba54310b76cb6c43a5634bf2724/8acbba54310b76cb6c43a5634bf2724.obj";
                //string tmp_asset_path = "Assets/Models/sel_objs/test_mine/";
                string tmp_asset_path = GetArg ("-outputDir");;
                string[] dir = Directory.GetDirectories(tmp_asset_path);
                foreach (string d_tmp in dir) {
                    //Debug.Log(d_tmp);
                    string data_new_path = d_tmp + d_tmp.Remove(0, d_tmp.LastIndexOf ('/')) + ".obj";
                    Debug.Log(data_new_path);

                    allSelected.Add (AssetDatabase.LoadMainAssetAtPath(data_new_path) as GameObject, data_new_path);
                }
                //allSelected.Add (AssetDatabase.LoadMainAssetAtPath(tmp_asset_path) as GameObject, tmp_asset_path);

        if (allSelected == null || allSelected.Count == 0)
            return;

        List<GameObject> toRemove = new List<GameObject> ();
        foreach (KeyValuePair<GameObject, string> entry in allSelected) {
            if (entry.Key == null || PrefabUtility.GetPrefabType (entry.Key) != PrefabType.ModelPrefab) {
                toRemove.Add (entry.Key);
            }
        }

        foreach (GameObject entry in toRemove) {
            allSelected.Remove (entry);
        }

        foreach (KeyValuePair<GameObject, string> entry in allSelected) {
            string loadingDirectory = "Assets/Models/";

            if (!entry.Value.StartsWith (loadingDirectory)) {
                Debug.LogError ("Selected Assets are not contained within " + loadingDirectory + " directory. Please move or copy assets to this directory, select them from there and try again.");
            } else {
                //get rid of location in hierarchy

                string subPathWithFileType = entry.Value.Remove (0, loadingDirectory.Length);
                //get rid of file type
                                //Debug.Log(subPathWithFileType);
                string subPathWithoutFileType = subPathWithFileType.Remove (subPathWithFileType.LastIndexOf ('.'));
                //get rid of file name
                string subPathWithoutFilename = subPathWithoutFileType.Remove (subPathWithoutFileType.LastIndexOf ('/'));

                //if directory does not already exist, make one
        //				System.IO.Directory.CreateDirectory(Application.dataPath + "/Resources/Prefabs/Converted Models/" + subPathWithoutFilename);
                System.IO.Directory.CreateDirectory (Application.dataPath + "/PrefabDatabase/GeneratedPrefabs/" + subPathWithoutFilename);

                Debug.Log (Application.dataPath + "/PrefabDatabase/GeneratedPrefabs/" + subPathWithoutFilename);

                //make meta file
                EditorApplication.Step ();

                //make prefab
                MakeSimplePrefabObj (entry.Key, subPathWithoutFileType);

                //force GC
                EditorApplication.SaveAssets ();
                Resources.UnloadUnusedAssets ();
                EditorUtility.UnloadUnusedAssetsImmediate ();

                GC.Collect ();
                EditorApplication.Step ();

            }
        }

                allSelected = new Dictionary<GameObject, string> ();

                tmp_asset_path = GetArg ("-outputDir");
                tmp_asset_path = tmp_asset_path.Replace("/Models/", "/PrefabDatabase/GeneratedPrefabs/");
                dir = Directory.GetDirectories(tmp_asset_path);
                foreach (string d_tmp in dir) {
                    //Debug.Log(d_tmp);
                    string data_new_path = d_tmp + d_tmp.Remove(0, d_tmp.LastIndexOf ('/')) + ".prefab";
                    Debug.Log(data_new_path);
                    allSelected.Add (AssetDatabase.LoadMainAssetAtPath(data_new_path) as GameObject, data_new_path);
                }

        AssetBundleBuild[] buildMap = new AssetBundleBuild[allSelected.Count];

        int loop_counter = 0;
        foreach (KeyValuePair<GameObject, string> entry in allSelected) {
            string _bundleName;
            string[] _assetPath = new string[1];
            _bundleName = entry.Key.name + ".bundle";
            // In case prefabs had some kind of file extension replace the file extension with .bundle
            //			_bundleName = _bundleName.Remove(_bundleName.LastIndexOf('.')) + ".bundle";

            buildMap [loop_counter].assetBundleName = _bundleName;
            _assetPath [0] = entry.Value;
            buildMap [loop_counter].assetNames = _assetPath;
            loop_counter++;
        }

        BuildPipeline.BuildAssetBundles ("Assets/PrefabDatabase/AssetBundles/Separated",
            buildMap,
            BuildAssetBundleOptions.None,
            BuildTarget.StandaloneOSXUniversal
        );
    }
Пример #43
0
    void OnGUI()
    {
#if false
        mAssetImporter.assetBundleName    = ""; //アセット名設定
        mAssetImporter.assetBundleVariant = ""; //拡張子設定
        mAssetImporter.userData           = ""; //ユーザーデータ

        if (mBuildMap == null)
        {
            mBuildMap = new AssetBundleBuild[1];
        }

        mBuildMap[0].assetBundleName    = "";
        mBuildMap[0].assetBundleVariant = "";
        mBuildMap[0].assetNames         = new string[]
        {
            "",
        };

        GUILayout.Label("Base Settings", EditorStyles.boldLabel);
        myString = EditorGUILayout.TextField("Text Field", myString);


        EditorWindow.GetWindow <AssetBundleWindow>();

        //EditorApplication.hierarchyWindowItemOnGUI(0,new Rect(0 ,0 ,100,100));

        groupEnabled = EditorGUILayout.BeginToggleGroup("Optional Settings", groupEnabled);
        myBool       = EditorGUILayout.Toggle("Toggle", myBool);
        myFloat      = EditorGUILayout.Slider("Slider", myFloat, -3, 3);
        EditorGUILayout.EndToggleGroup();
#endif

        //Pathを指定してその配下にある全ファイルのGUIDを取得
        var guids = AssetDatabase.FindAssets("", new[] { "Assets/Resources" });


        GUILayout.Label("Base Settings", EditorStyles.boldLabel);


        foreach (var guid in guids)
        {
            // GUIDからAssetPathを取得
            string path = AssetDatabase.GUIDToAssetPath(guid);

            // PathからAsset取得
            AssetImporter asip = AssetImporter.GetAtPath(path);

            // assetBundleNameとAssetPathがすでに一緒だったら何もしない
            if (asip.assetBundleName != path.ToLower())
            {
                Debug.Log("assetBundleName path = " + path);

                path = EditorGUILayout.TextField("Asset Name", path);

                // AssetPathを名前に設定
                asip.assetBundleName = path;
            }

            // AssetVariantsを設定
            asip.assetBundleVariant = "";
        }
    }
Пример #44
0
    public static void ExportMap(string override_asset_bundle_name, bool use_version_numbering, bool run_game_after_export = false)
    {
        IEnumerator routine()
        {
            var scene = SceneManager.GetActiveScene();

            var start_time = DateTime.Now;

            EditorSceneManager.SaveScene(scene);

            yield return(ProcessScene(scene));

            var bundle_name = scene.name;

            if (use_version_numbering)
            {
                var version = EditorPrefs.GetInt($"{scene.name}_version", 1);

                version++;

                EditorPrefs.SetInt($"{scene.name}_version", version);

                bundle_name = $"{scene.name} v{version}";
            }

            if (string.IsNullOrEmpty(override_asset_bundle_name) == false)
            {
                bundle_name = override_asset_bundle_name;
            }

            var build = new AssetBundleBuild
            {
                assetBundleName = bundle_name,
                assetNames      = new[] { scene.path }
            };

            if (!Directory.Exists(ASSET_BUNDLES_BUILD_PATH))
            {
                Directory.CreateDirectory(ASSET_BUNDLES_BUILD_PATH);
            }

            BuildPipeline.BuildAssetBundles(ASSET_BUNDLES_BUILD_PATH, new [] { build }, BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.StandaloneWindows);

            var time_taken = start_time - DateTime.Now;

            Debug.Log($"BuildAssetBundles took {time_taken:mm\\:ss}");

            var bundle_path = Path.Combine(Application.dataPath.Replace("/Assets", "/AssetBundles"), build.assetBundleName);

            var map_dir   = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "SkaterXL/Maps");
            var dest_path = Path.Combine(map_dir, build.assetBundleName);

            if (Directory.Exists(map_dir))
            {
                Debug.Log($"Copying {bundle_path} to {dest_path}");

                File.Copy(bundle_path, dest_path, overwrite: true);
                File.Delete(bundle_path);
            }
            else
            {
                Debug.Log($"SkaterXL Maps folder not found at '{dest_path}', asset bundle saved to '{bundle_name}'");
            }

            EditorSceneManager.OpenScene(scene.path);

            if (run_game_after_export)
            {
                Application.OpenURL("steam://run/962730");
            }
        }

        EditorCoroutineUtility.StartCoroutineOwnerless(routine());
    }
Пример #45
0
	/// <summary>
	/// Builds the asset bundles.
	/// </summary>
	/// <param name="szPackageName">Size package name.</param>
	/// <param name="outZipFile">If set to <c>true</c> out zip file.</param>
	/// <param name="cleaup">If set to <c>true</c> cleaup.</param>
	/// <param name="szDirectory">Size directory.</param>
	/// <param name="szPattern">Size pattern.</param>
	public static bool 	BuildAssetBundles(string szInputPath, SearchFileType type)
	{
		if (string.IsNullOrEmpty(szInputPath))
			throw new System.NullReferenceException();

		// create mid path
		if (!Directory.Exists(MidPath))
			Directory.CreateDirectory(MidPath);

		// Search all files 
		List<string> aryFile = SearchFile(type, szInputPath);
		if (aryFile.Count <= 0)
			return false;

		// get directory name 
		string[] arySplit = szInputPath.Split('/');
		if (arySplit.Length <= 0)
			return false;

		AssetBundleBuild ab 	= new AssetBundleBuild();
		ab.assetNames			= aryFile.ToArray();
		ab.assetBundleVariant	= SearchFileType.unity3d.ToString();
		ab.assetBundleName		= arySplit[arySplit.Length - 1];
	
		// get the assetbundl file path
		string szOutPath = MidPath.Substring(
			Application.dataPath.Length - 6, MidPath.Length - Application.dataPath.Length + 6
			);

		BuildPipeline.BuildAssetBundles(szOutPath, new AssetBundleBuild[]{ab}, 
			BuildAssetBundleOptions.UncompressedAssetBundle, EditorUserBuildSettings.activeBuildTarget);

		return true;
	}
Пример #46
0
    public static bool BuildBundle(BuildTarget buildTarget, out string filepath, bool ignoreGraphCacheWarning)
    {
        filepath = "";

        Debug.ClearDeveloperConsole();
        Debug.Log("\n\n");
        Debug.Log("\n--- Building map ---");

        AssetBundleBuild build = new AssetBundleBuild();

        if (!AssetDatabase.IsValidFolder(PATH))
        {
            Debug.Log("No Export folder found, creating one.");
            AssetDatabase.CreateFolder("Assets", "Export");
        }

        try {
            EditorSceneManager.SaveOpenScenes();

            if (!SanityCheck.DoSanityCheck(ignoreGraphCacheWarning))
            {
                Debug.Log("Sanity check failed, aborting export!");
                return(false);
            }



            //Bundle graphcache if available.
            TextAsset graphCacheAsset           = CacheGenerator.GetGraphCacheFile();
            TextAsset graphCacheCoverPointAsset = CacheGenerator.GetGraphCacheCoverPointFile();

            if (graphCacheAsset != null && graphCacheCoverPointAsset != null)
            {
                Debug.Log("Graphcache was found, bundling!");
                SetupGraphCache(graphCacheAsset, graphCacheCoverPointAsset);
                EditorSceneManager.SaveOpenScenes();
            }
            else
            {
                Debug.Log("WARNING: Couldn't find graphcache.");
            }

            Scene currentScene = EditorSceneManager.GetSceneAt(0);

            build.assetBundleName = currentScene.name + ".rfl";

            List <string> assetNames = new List <string>();

            assetNames.Add(currentScene.path);


            build.assetNames = assetNames.ToArray();

            AssetBundleBuild[] buildMap = new AssetBundleBuild[] { build };

            BuildPipeline.BuildAssetBundles(PATH, buildMap, BuildAssetBundleOptions.None, buildTarget);
        }
        catch (System.Exception e) {
            EditorUtility.DisplayDialog("Could not export map", "Could not create the .rfl file.\n\nDetails: " + e.Message, "Ok");
            Debug.LogException(e);
            return(false);
        }

        Debug.Log("Successfully exported " + build.assetBundleName);

        if (Paths.HasExecutablePath())
        {
            string exportPath = Paths.ProjectPath() + PATH + "/" + build.assetBundleName;

            string levelDestinationPath = Paths.ExecutableToolsStagingPath() + "/" + build.assetBundleName;

            try {
                File.Copy(exportPath, levelDestinationPath, true);
            }
            catch (System.Exception e) {
                EditorUtility.DisplayDialog("Could not export map", "Could not copy map to the mod staging folder.\n\nDetails: " + e.Message, "Ok");
                Debug.LogException(e);
                return(false);
            }

            Debug.Log("Copied exported map to " + levelDestinationPath);
            filepath = levelDestinationPath;
            return(true);
        }

        return(false);
    }
Пример #47
0
    public static void CreatePrefabFromModel_script()
    {
        Dictionary<GameObject, string> allSelected = new Dictionary<GameObject, string> ();
        Dictionary<string, string> path_to_id = new Dictionary<string, string> ();
        // argument -inputFile is for the txt file with each line of "obj-path,_id"
        string tmp_doc_path = GetArg ("-inputFile");;
        StreamReader theReader = new StreamReader (tmp_doc_path, Encoding.Default);
        string line;

        // Get the obj path and add it to the dictionary for further processing
        using (theReader) {
            do {
                line = theReader.ReadLine ();
                if (line != null){
                    Debug.Log(line);
                    string now_obj_path     = line.Substring(0, line.LastIndexOf(','));
                    string now_id           = line.Substring(line.LastIndexOf(',')+1, line.Length -(line.LastIndexOf(',')+1));
                    //Debug.Log(now_obj_path);
                    //Debug.Log(now_id);

                    /*
                    if ((now_obj_path.ToLowerInvariant ().EndsWith (".obj")) || (now_obj_path.ToLowerInvariant ().EndsWith (".obj,"))) {
                        AssetDatabase.ImportAsset (now_obj_path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ImportRecursive);
                    }
                    */

                    allSelected.Add (AssetDatabase.LoadMainAssetAtPath(now_obj_path) as GameObject, now_obj_path);
                    path_to_id.Add (now_obj_path, now_id);
                }
            } while (line != null);
            theReader.Close ();
        }

        // Generate prefabs from the dictionary
        if (allSelected == null || allSelected.Count == 0)
            return;

        List<GameObject> toRemove = new List<GameObject> ();
        foreach (KeyValuePair<GameObject, string> entry in allSelected) {
            if (entry.Key == null || PrefabUtility.GetPrefabType (entry.Key) != PrefabType.ModelPrefab) {
                toRemove.Add (entry.Key);
            }
        }

        foreach (GameObject entry in toRemove) {
            allSelected.Remove (entry);
        }

        string saving_directory     = Application.dataPath + "/PrefabDatabase/GeneratedPrefabs/objs_by_id/";
        System.IO.Directory.CreateDirectory(saving_directory);

        foreach (KeyValuePair<GameObject, string> entry in allSelected) {
            //make meta file
            EditorApplication.Step ();

            //make prefab
            MakeSimplePrefabObj (entry.Key, "objs_by_id/" + path_to_id[entry.Value]);

            //force GC
            EditorApplication.SaveAssets ();
            Resources.UnloadUnusedAssets ();
            EditorUtility.UnloadUnusedAssetsImmediate ();

            GC.Collect ();
            EditorApplication.Step ();

        }

        // Get the available prefabs and generate assetbundles from them
        allSelected = new Dictionary<GameObject, string> ();
        foreach (KeyValuePair<string, string> entry in path_to_id){
            string data_new_path    = "Assets/PrefabDatabase/GeneratedPrefabs/objs_by_id/" + entry.Value + ".prefab";
            allSelected.Add (AssetDatabase.LoadMainAssetAtPath(data_new_path) as GameObject, data_new_path);
        }
        AssetBundleBuild[] buildMap = new AssetBundleBuild[allSelected.Count];

        int loop_counter = 0;
        foreach (KeyValuePair<GameObject, string> entry in allSelected) {
            string _bundleName;
            string[] _assetPath = new string[1];
            _bundleName = entry.Key.name + ".bundle";
            // In case prefabs had some kind of file extension replace the file extension with .bundle
            //			_bundleName = _bundleName.Remove(_bundleName.LastIndexOf('.')) + ".bundle";

            buildMap [loop_counter].assetBundleName = _bundleName;
            _assetPath [0] = entry.Value;
            buildMap [loop_counter].assetNames = _assetPath;
            loop_counter++;
        }

        string bundle_prefix    = "Assets/PrefabDatabase/AssetBundles/Separated";
        BuildPipeline.BuildAssetBundles (bundle_prefix,
            buildMap,
            BuildAssetBundleOptions.None,
            BuildTarget.StandaloneOSXUniversal
        );

        // Write the information into the text file indicated by -outputFile
        string[] all_bundle_path    = new string[allSelected.Count];
        int now_indx                = 0;
        foreach (KeyValuePair<GameObject, string> entry in allSelected) {
            string _bundleName;
            _bundleName = entry.Key.name + ".bundle";
            _bundleName = bundle_prefix + "/" + _bundleName;
            all_bundle_path[now_indx]   = _bundleName;
            now_indx++;
        }

        using (StreamWriter sw = new StreamWriter(GetArg ("-outputFile")))
        {
            foreach (string d_tmp in all_bundle_path) {
                //sw.Write("This is line for ");
                //sw.WriteLine(d_tmp);
                string data_new_path = d_tmp;
                sw.Write(d_tmp.Remove(0, d_tmp.LastIndexOf ('/')+1));
                sw.Write(",");
                Debug.Log(data_new_path);

                //allSelected.Add (AssetDatabase.LoadMainAssetAtPath(data_new_path) as GameObject, data_new_path);
                AssetBundle loadedAssetBundle = AssetBundle.LoadFromFile (data_new_path);
                if (loadedAssetBundle == null) {
                    Debug.Log ("Failed to load AssetBundle!");
                    continue;
                }
                GameObject gObj = loadedAssetBundle.LoadAsset<GameObject> (loadedAssetBundle.GetAllAssetNames () [0]);
                GeneratablePrefab[] prefab = gObj.GetComponents<GeneratablePrefab> ();
                loadedAssetBundle.Unload (false);
                sw.Write(prefab[0].myComplexity);
                sw.Write(",");
                sw.Write(prefab[0].myBounds);
                sw.Write(",");
                sw.Write(prefab[0].isLight);
                sw.Write(",");
                sw.Write(prefab[0].attachMethod);
                sw.Write("\n");
            }

        }
    }
Пример #48
0
    public static void BuildBundles(string bundlePath, BuildTarget target, BuildAssetBundleOptions assetBundleOptions)
    {
        Debug.Log("Verifying asset registries ..");
        var ok = TestRegistries();

        if (!ok)
        {
            Debug.LogError("Asset registries appear broken.... Build failed.");
            return;
        }

        PrepareRegistries();

        Debug.Log("Building asset registries ..");

        var guids = AssetDatabase.FindAssets("t:" + typeof(AssetRegistryRoot).Name);

        foreach (var guid in guids)
        {
            var builds = new List <AssetBundleBuild>();

            var path         = AssetDatabase.GUIDToAssetPath(guid);
            var registryRoot = AssetDatabase.LoadAssetAtPath <AssetRegistryRoot>(path);

            if (registryRoot.assetRegistries == null)
            {
                continue;
            }

            // Register asset registry bundle
            var registryBundleName = path;
            registryBundleName = registryBundleName.Replace("Assets/", "");
            registryBundleName = registryBundleName.Replace(".asset", "");

            Debug.Log("Building resource bundles for asset registry:" + registryBundleName);

            var paths = new List <string>();
            paths.Add(AssetDatabase.GetAssetPath(registryRoot));
            var build = new AssetBundleBuild();
            build.assetBundleName    = registryBundleName;
            build.assetBundleVariant = "";
            build.assetNames         = paths.ToArray();

            builds.Add(build);

            // Register single asset bundles
            var singleAssetFolder = registryBundleName + "_Assets";
            //singleAssetFolder = singleAssetFolder.ToLower();
            if (!Directory.Exists(singleAssetFolder))
            {
                Directory.CreateDirectory(singleAssetFolder);
            }


            var singleAssetGUIDs = new List <string>();

            // Get single assets from registries
            foreach (var registry in registryRoot.assetRegistries)
            {
                var baseRegistry = registry as RegistryBase;
                if (baseRegistry != null)
                {
                    baseRegistry.GetSingleAssetGUIDs(singleAssetGUIDs, registryRoot.serverBuild);
                }
            }

            // Build single asset bundles
            var singleAssetBundlesHandled = new List <string>();
            foreach (var singleAssetBundleGUID in singleAssetGUIDs)
            {
                if (singleAssetBundleGUID == null || singleAssetBundleGUID == "")
                {
                    continue;
                }

                if (singleAssetBundlesHandled.Contains(singleAssetBundleGUID))
                {
                    continue;
                }

                path = AssetDatabase.GUIDToAssetPath(singleAssetBundleGUID);

                build = new AssetBundleBuild();
                build.assetBundleName    = singleAssetFolder + "/" + singleAssetBundleGUID;
                build.assetBundleVariant = "";
                build.assetNames         = new string[] { path };

                Debug.Log("Creating single asset bundle from asset:" + path + " Bundle name:" + build.assetBundleName);

                builds.Add(build);
                singleAssetBundlesHandled.Add(singleAssetBundleGUID);
            }


            // TODO (mogensh) Settle on what buildpipline to use. LegacyBuildPipeline uses SBP internally and is faster.
            //            LegacyBuildPipeline.BuildAssetBundles(bundlePath, builds.ToArray(), assetBundleOptions, target);
            BuildPipeline.BuildAssetBundles(bundlePath, builds.ToArray(), assetBundleOptions, target);

            // Set write time so tools can show time since build
            Directory.SetLastWriteTime(bundlePath, DateTime.Now);
        }
    }
Пример #49
0
        /// <summary>
        /// 得到一个目录下的所有的目录对应的ABB
        /// </summary>
        private AssetBundleBuild[] GetOneDir_Dirs()
        {
            DirectoryInfo rDirInfo = new DirectoryInfo(bundleInfo.assetPath);
            if (!rDirInfo.Exists) return null;

            List<AssetBundleBuild> rABBList = new List<AssetBundleBuild>();
            DirectoryInfo[] rSubDirs = rDirInfo.GetDirectories();
            for (int i = 0; i < rSubDirs.Length; i++)
            {
                string rDirPath = rSubDirs[i].FullName;
                string rFileName = "";
                if (Application.platform == RuntimePlatform.WindowsEditor)
                {
                    string rRootPath = System.Environment.CurrentDirectory + "\\";
                    rDirPath = rDirPath.Replace(rRootPath, "").Replace("\\", "/");
                    rFileName = Path.GetFileNameWithoutExtension(rDirPath);
                }
                else if (Application.platform == RuntimePlatform.OSXEditor)
                {
                    string rRootPath = System.Environment.CurrentDirectory + "/";
                    rDirPath = rDirPath.Replace(rRootPath, "");
                    rFileName = Path.GetFileNameWithoutExtension(rDirPath);
                }
                else
                {
                    throw new System.NotSupportedException("当前运行平台不支持打包操作");
                }

                AssetBundleBuild rABB = new AssetBundleBuild();
                rABB.assetBundleName = bundleInfo.name + "/" + rFileName;
                rABB.assetNames = new string[] { rDirPath };
                rABB.assetBundleVariant = Global.BundleExtName;
                rABBList.Add(rABB);
            }
            return rABBList.ToArray();
        }
    public static void ExportPackage(GameObject gameObject, string path, string typeName, PackageJSON packageJSON)
    {
        string fileName        = Path.GetFileName(path);
        string folderPath      = Path.GetDirectoryName(path);
        string androidFileName = Path.GetFileNameWithoutExtension(path) + "_android";
        string pcFileName      = Path.GetFileNameWithoutExtension(path) + "_pc";

        Selection.activeObject = gameObject;
        EditorSceneManager.MarkSceneDirty(gameObject.scene);
        EditorSceneManager.SaveScene(gameObject.scene);

        PrefabUtility.SaveAsPrefabAsset(Selection.activeObject as GameObject, $"Assets/_{typeName}.prefab");
        AssetBundleBuild assetBundleBuild = default;

        assetBundleBuild.assetNames      = new string[] { $"Assets/_{typeName}.prefab" };
        assetBundleBuild.assetBundleName = pcFileName;

        // Build for PC
        BuildTargetGroup selectedBuildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;
        BuildTarget      activeBuildTarget        = EditorUserBuildSettings.activeBuildTarget;

        BuildPipeline.BuildAssetBundles(Application.temporaryCachePath, new AssetBundleBuild[] { assetBundleBuild }, 0, BuildTarget.StandaloneWindows64);

        // Do it again for Android
        assetBundleBuild.assetBundleName = androidFileName;
        BuildPipeline.BuildAssetBundles(Application.temporaryCachePath, new AssetBundleBuild[] { assetBundleBuild }, 0, BuildTarget.Android);

        EditorPrefs.SetString("currentBuildingAssetBundlePath", folderPath);

        // JSON stuff
        packageJSON.androidFileName = androidFileName;
        packageJSON.pcFileName      = pcFileName;
        string json = JsonUtility.ToJson(packageJSON, true);

        File.WriteAllText(Application.temporaryCachePath + "/package.json", json);
        AssetDatabase.DeleteAsset($"Assets/_{typeName}.prefab");

        // Delete the zip if it already exists and re-zip
        if (File.Exists(Application.temporaryCachePath + "/tempZip.zip"))
        {
            File.Delete(Application.temporaryCachePath + "/tempZip.zip");
        }
        CreateZipFile(Application.temporaryCachePath + "/tempZip.zip", new List <string> {
            Application.temporaryCachePath + "/" + pcFileName, Application.temporaryCachePath + "/" + androidFileName, Application.temporaryCachePath + "/package.json"
        });
        if (File.Exists(path))
        {
            File.Delete(path);
        }
        File.Move(Application.temporaryCachePath + "/tempZip.zip", path);
        UnityEngine.Object.DestroyImmediate(gameObject);

        /*if (File.Exists(path))
         * {
         *  File.Delete(path);
         * }
         * Debug.Log(path);
         * //File.Move(Application.temporaryCachePath + "/PC_" + fileName, path);
         * //File.Move(Application.temporaryCachePath + "/Android_" + fileName, path);
         * AssetDatabase.Refresh();
         * //EditorUtility.DisplayDialog("Exportation Successful!", "Exportation Successful!", "OK");*/
        AssetDatabase.Refresh();
    }
Пример #51
0
        /// <summary>
        /// 得到一个文件的ABB
        /// </summary>
        private AssetBundleBuild[] GetOneFile()
        {
            Object rObj = AssetDatabase.LoadAssetAtPath(bundleInfo.assetPath, typeof(Object));
            if (rObj == null) return null;

            AssetBundleBuild rABB = new AssetBundleBuild();
            rABB.assetBundleName = bundleInfo.name;
            rABB.assetNames = new string[] { bundleInfo.assetPath };
            rABB.assetBundleVariant = Global.BundleExtName;
            return new AssetBundleBuild[] { rABB };
        }
Пример #52
0
    static AssetBundleBuild?CreateAssetBundleBuild(string assetDir, string assetBundleName, List <string> excludes)
    {
        var ab = new AssetBundleBuild();

        ab.assetBundleName = assetBundleName + ".fg";

        // 如果上次打包以来为更新过此 bundle 未编辑过则跳过
        long newWriteTime   = 0;
        long lastWriteTime  = 0;
        var  flastWriteTime = assetDir + @"/.lastWriteTime";

        if (File.Exists(flastWriteTime))
        {
            StreamReader reader = new StreamReader(flastWriteTime);
            if (reader != null)
            {
                string s = reader.ReadLine();
                reader.Close();
                if (!long.TryParse(s, out lastWriteTime))
                {
                    lastWriteTime = 0;
                }
                newWriteTime = lastWriteTime;
            }
        }

        var assetNames = new List <string>();
        int nnew       = 1; // =0

        foreach (var f in Directory.GetFiles(assetDir, "*.*", SearchOption.AllDirectories))
        {
            if (excludes.Contains(Path.GetExtension(f)) ||
                Path.GetFileName(f) == ".lastWriteTime")
            {
                continue;
            }
            assetNames.Add(f);

            var finfo = new FileInfo(f);
            if (finfo.LastWriteTime.ToFileTimeUtc() > newWriteTime)
            {
                ++nnew;
                newWriteTime = finfo.LastWriteTime.ToFileTimeUtc();
                UnityEngine.Debug.Log(UPath.go(f) + ": " + DateTime.FromFileTimeUtc(newWriteTime));
            }
        }
        ab.assetNames = assetNames.ToArray();

        if (nnew > 0)
        {
            StreamWriter writer = new StreamWriter(flastWriteTime);
            writer.Write(newWriteTime);
            writer.Close();
            UnityEngine.Debug.Log(assetDir + "> " + DateTime.FromFileTimeUtc(newWriteTime));

            return(ab);
        }
        else
        {
            return(null);
        }
    }
	static public void BuildABs(string[] assets, string outPath,string abName, BuildAssetBundleOptions bbo)
	{
		AssetBundleBuild[] bab = new AssetBundleBuild[1];
		bab[0].assetBundleName = abName;//打包的资源包名称 随便命名
		bab[0].assetNames = assets;

		BuildPipeline.BuildAssetBundles (outPath, bab, bbo, target);
//		BuildPipeline.BuildAssetBundle(main, assets, pathName, bbo, target);

	}
 private Dictionary <string, ArtRes> CheckAssetBundleResources(List <string> dirList)
 {
     if (m_Loader == null || dirList == null || dirList.Count <= 0)
     {
         return(null);
     }
     try {
         Dictionary <string, ArtRes> ret = null;
         for (int i = 0; i < dirList.Count; ++i)
         {
             string dir = dirList[i];
             if (string.IsNullOrEmpty(dir))
             {
                 continue;
             }
             if (!Directory.Exists(dir))
             {
                 continue;
             }
             string[] files = Directory.GetFiles(dir, "*.*", SearchOption.TopDirectoryOnly);
             if (files == null || files.Length <= 0)
             {
                 continue;
             }
             for (int j = 0; j < files.Length; ++j)
             {
                 float  process  = ((float)j) / ((float)files.Length);
                 string fileName = files[j];
                 if (string.IsNullOrEmpty(fileName))
                 {
                     continue;
                 }
                 fileName = fileName.Replace('\\', '/').ToLower();
                 EditorUtility.DisplayProgressBar("正在检查资源", fileName, process);
                 string    parentAssetName = AssetBunbleInfo.GetBundleFileName(fileName, true, false);
                 AssetInfo parentInfo      = m_Loader.FindAssetInfo(parentAssetName);
                 if (parentInfo == null)
                 {
                     continue;
                 }
                 string   parentAssetBundleName = Path.GetFileName(parentInfo.FileName);
                 string[] depFileNames          = AssetDatabase.GetDependencies(fileName);
                 for (int k = 0; k < depFileNames.Length; ++k)
                 {
                     string depFileName = depFileNames[k];
                     if (string.IsNullOrEmpty(depFileName))
                     {
                         continue;
                     }
                     string    assetName = AssetBunbleInfo.GetBundleFileName(depFileName, true, false).ToLower();
                     AssetInfo assetInfo = m_Loader.FindAssetInfo(assetName);
                     if (assetInfo == null)
                     {
                         if (ret == null)
                         {
                             ret = new Dictionary <string, ArtRes>();
                         }
                         if (!ret.ContainsKey(depFileName))
                         {
                             ArtRes res = new ArtRes();
                             res.refCount = 1;
                             System.Type resType = AssetBundleBuild.GetResourceExtType(depFileName);
                             if (resType == null)
                             {
                                 continue;
                             }
                             res.resType        = resType;
                             res.includeBundles = new HashSet <string>();
                             res.includeBundles.Add(parentAssetBundleName);
                             ret.Add(depFileName, res);
                         }
                         else
                         {
                             ArtRes res = ret[depFileName];
                             res.refCount    += 1;
                             ret[depFileName] = res;
                             if (!res.includeBundles.Contains(parentAssetBundleName))
                             {
                                 res.includeBundles.Add(parentAssetBundleName);
                             }
                         }
                     }
                 }
             }
         }
         return(ret);
     } finally {
         EditorUtility.ClearProgressBar();
     }
 }
Пример #55
0
    static void ExportSceneResource()
    {
        VRCSDK2.VRC_SceneDescriptor Desc = ( Selection.activeObject as GameObject ).GetComponent<VRCSDK2.VRC_SceneDescriptor>();
        if( Desc == null )
        {
            UnityEditor.EditorUtility.DisplayDialog("Build Custom Scene", "You must place a VRC_SceneDescriptor on the root of you custom scene", "Ok" );
            return;
        }
        if( Desc.spawns.Length < 1 )
        {
            UnityEditor.EditorUtility.DisplayDialog("Build Custom Scene", "You must add at least one spawn to spawns in your VRC_SceneDescriptor.", "Ok" );
            return;
        }

        //if( CheckCompatibility( Selection.activeObject as GameObject ) > 0 )
        //{
        //    UnityEditor.EditorUtility.DisplayDialog("Build Custom Scene", "Your scene contains depricated scripts. See the error log.", "Ok" );
        //    return;
        //}

        ListDynamicPrefabs( Desc.DynamicPrefabs, Selection.activeObject as GameObject );
        const int SyncIdStart = 500;
        const int SyncIdMax = 500;
        int SyncCount = AssignSyncIds( SyncIdStart, Selection.activeObject as GameObject ) - SyncIdStart;
        if( SyncCount > SyncIdMax )
        {
            UnityEditor.EditorUtility.DisplayDialog("Build Custom Scene", "Your scene contains too many VRC_ObjectApi scripts for synchronization.", "Ok" );
            return;
        }

        Desc.LightMode = LightmapSettings.lightmapsMode;
        switch( LightmapSettings.lightmapsMode )
        {
        case LightmapsMode.NonDirectional:
            Desc.LightMapsFar = new Texture2D[ LightmapSettings.lightmaps.Length ];
            Desc.LightMapsNear = null;
            break;
        case LightmapsMode.CombinedDirectional:
            Desc.LightMapsFar = new Texture2D[ LightmapSettings.lightmaps.Length ];
            Desc.LightMapsNear = new Texture2D[ LightmapSettings.lightmaps.Length ];
            break;
        case LightmapsMode.SeparateDirectional:
            Desc.LightMapsFar = new Texture2D[ LightmapSettings.lightmaps.Length ];
            Desc.LightMapsNear = new Texture2D[ LightmapSettings.lightmaps.Length ];
            break;
        }

        for( int i = 0; i < LightmapSettings.lightmaps.Length; ++i )
        {
            Desc.LightMapsFar[i] = LightmapSettings.lightmaps[i].lightmapFar;
            if( Desc.LightMapsNear != null )
                Desc.LightMapsNear[i] = LightmapSettings.lightmaps[i].lightmapNear;
        }

        List<VRCSDK2.VRC_LightmapReference> lightMapReferences = AddLightmapReferences(Desc.gameObject);
        List<VRCSDK2.VRC_ReflectionReference> reflectionReferences = AddReflectionReferences(Desc.gameObject);
        List<VRCSDK2.VRC_StaticReference> staticReferences = AddStaticReferences(Desc.transform);

        Desc.LoadRenderSettings = true;

        Desc.RenderAmbientEquatorColor = RenderSettings.ambientEquatorColor;
        Desc.RenderAmbientGroundColor = RenderSettings.ambientGroundColor;
        Desc.RenderAmbientIntensity = RenderSettings.ambientIntensity;
        Desc.RenderAmbientLight = RenderSettings.ambientLight;
        Desc.RenderAmbientMode = RenderSettings.ambientMode;
        Desc.RenderAmbientProbe = RenderSettings.ambientProbe;
        Desc.RenderAmbientSkyColor = RenderSettings.ambientSkyColor;

        Desc.RenderFog = RenderSettings.fog;
        Desc.RenderFogColor = RenderSettings.fogColor;
        Desc.RenderFogMode = RenderSettings.fogMode;
        Desc.RenderFogDensity = RenderSettings.fogDensity;
        Desc.RenderFogLinearStart = RenderSettings.fogStartDistance;
        Desc.RenderFogLinearEnd = RenderSettings.fogEndDistance;

        Desc.RenderHaloStrength = RenderSettings.haloStrength;
        Desc.RenderFlareFadeSpeed = RenderSettings.flareFadeSpeed;
        Desc.RenderFlareStrength = RenderSettings.flareStrength;

        Desc.RenderCustomReflection = RenderSettings.customReflection;
        Desc.RenderDefaultReflectionMode = RenderSettings.defaultReflectionMode;
        Desc.RenderDefaultReflectionResolution = RenderSettings.defaultReflectionResolution;
        Desc.RenderReflectionBounces = RenderSettings.reflectionBounces;
        Desc.RenderReflectionIntensity = RenderSettings.reflectionIntensity;

        Desc.RenderSkybox = RenderSettings.skybox;

        PrefabUtility.CreatePrefab("Assets/_CustomScene.prefab", Selection.activeObject as GameObject);
        AssetBundleBuild abb = new AssetBundleBuild();
        abb.assetNames = new string[] { "Assets/_CustomScene.prefab" };
        abb.assetBundleName = "customScene.unity3d";

        string vrcsPath = EditorUtility.SaveFilePanel("Save Custom Scene", "", "NewScene", "vrcs");
        string tmpAssetBundlePath = Application.temporaryCachePath + "/" + abb.assetBundleName;

        if (vrcsPath.Length != 0)
        {
            BuildTarget InitialTarget = EditorUserBuildSettings.activeBuildTarget;
            BuildPipeline.BuildAssetBundles(Application.temporaryCachePath, new AssetBundleBuild[] { abb }, BuildAssetBundleOptions.UncompressedAssetBundle);
            lzma.LzmaUtilEncode(tmpAssetBundlePath, vrcsPath);
            recentlySavedPath = vrcsPath;
            EditorUserBuildSettings.SwitchActiveBuildTarget(InitialTarget);
        }

        AssetDatabase.DeleteAsset( "Assets/_CustomScene.prefab" );
        AssetDatabase.Refresh();

        foreach (VRCSDK2.VRC_ReflectionReference rr in reflectionReferences)
            DestroyImmediate(rr);
        foreach (VRCSDK2.VRC_LightmapReference lmr in lightMapReferences)
            DestroyImmediate(lmr);
        lightMapReferences.Clear();
        foreach (VRCSDK2.VRC_StaticReference sr in staticReferences)
            DestroyImmediate(sr);
        staticReferences.Clear();

        VRCSDK2.VRC_Editor.RecordActivity( "scene", Path.GetFileName( vrcsPath ) );
    }
Пример #56
0
    public static void BuildWin()
    {
        string outDir = Path.Combine(Application.streamingAssetsPath, AssetBundleHelp.Abs_Out_Dir);
        BuildAssetBundleOptions buildOpt    = BuildAssetBundleOptions.None;
        BuildTarget             buildTarget = BuildTarget.StandaloneWindows;
        List <AssetBundleBuild> buildList   = new List <AssetBundleBuild>();

        string dataPathParentDir = Path.GetDirectoryName(Application.dataPath);

        BuildAssetBundleSetting babs = BuildAssetBundleSetting.ParseFile(BuildAssetBundleSetting.GetDefaultSettingFilePath());

        foreach (var setting in babs.bundleSettingMap.Values)
        {
            HashSet <string> assetNames = new HashSet <string>();

            {
                string absAssetDir = Path.Combine(Application.dataPath, setting.src);
                foreach (string fileFormat in setting.subfixs)
                {
                    var resFiles = Directory.GetFiles(absAssetDir, fileFormat, SearchOption.AllDirectories);
                    foreach (var elem in resFiles)
                    {
                        string assetPath = ExtractRelativePath(elem, dataPathParentDir);
                        bool   needPck   = true;
                        if (setting.excludes.TryGetValue(assetPath, out BuildAssetBundleSetting.PathSetting ps))
                        {
                            if (BuildAssetBundleSetting.IsPlatformMatch(ps.platforms))
                            {
                                needPck = false;
                            }
                        }
                        if (needPck)
                        {
                            assetNames.Add(assetPath);
                        }
                    }
                }
            }
            {
                foreach (var ps in setting.includes.Values)
                {
                    if (BuildAssetBundleSetting.IsPlatformMatch(ps.platforms))
                    {
                        assetNames.Add(ps.val);
                    }
                }
            }

            AssetBundleBuild abd = new AssetBundleBuild();
            abd.assetBundleName = setting.name;
            abd.assetNames      = new List <string>(assetNames).ToArray();
            if (abd.assetNames.Length > 0)
            {
                buildList.Add(abd);
            }
        }

        Directory.CreateDirectory(outDir);
        AssetBundleManifest buildRet = BuildPipeline.BuildAssetBundles(outDir, buildList.ToArray(), buildOpt, buildTarget);
        {
            Dictionary <string, AssetBundleMetaData> metaDatas = new Dictionary <string, AssetBundleMetaData>();

            var allBundles = buildRet.GetAllAssetBundles();
            foreach (var elem in allBundles)
            {
                var abDp   = buildRet.GetAllDependencies(elem);
                var abDdp  = buildRet.GetDirectDependencies(elem);
                var abHash = buildRet.GetAssetBundleHash(elem);
                var xx     = abHash;

                var metaData = new AssetBundleMetaData();
                metaData.bundleName         = elem;
                metaData.hash               = abHash.ToString();
                metaData.directDependencies = new List <string>(abDp);
                foreach (var buildInfo in buildList)
                {
                    if (buildInfo.assetBundleName == elem)
                    {
                        metaData.assetNames = new List <string>(buildInfo.assetNames);
                        break;
                    }
                }
                metaDatas.Add(metaData.bundleName, metaData);
            }

            foreach (var kv in metaDatas)
            {
                HashSet <string> dependencies = new HashSet <string>();
                Stack <string>   waitCheckDp  = new Stack <string>(kv.Value.directDependencies);

                while (waitCheckDp.Count > 0)
                {
                    string dp = waitCheckDp.Pop();
                    if (!dependencies.Contains(dp))
                    {
                        dependencies.Add(dp);
                        if (metaDatas.TryGetValue(dp, out AssetBundleMetaData dbMetaData))
                        {
                            foreach (var relateDp in dbMetaData.directDependencies)
                            {
                                if (!dependencies.Contains(relateDp))
                                {
                                    waitCheckDp.Push(relateDp);
                                }
                            }
                        }
                    }
                }
                dependencies.Remove(kv.Key);
                kv.Value.dependencies = new List <string>(dependencies);
            }


            // var jsonStr = JsonConvert.SerializeObject(new AssetBundleMetaDataMap() { datas = metaDatas }, Formatting.Indented);
            var jsonStr = JsonConvert.SerializeObject(metaDatas, Newtonsoft.Json.Formatting.Indented);
            // jsonStr = jsonStr + jsonStr;
            File.WriteAllText(Path.Combine(outDir, AssetBundleHelp.Asset_Bundle_Meta_Data_Name), jsonStr);
        }
    }
Пример #57
0
        static void RunAssetBundleBuild(string folder, List <string> environments, List <string> vehicles)
        {
            Directory.CreateDirectory(folder);

            var envManifests     = new List <Manifest>();
            var vehicleManifests = new List <Manifest>();

            if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                Debug.LogWarning("Cancelling the build.");
                return;
            }

            var currentScenes = new HashSet <Scene>();

            for (int i = 0; i < EditorSceneManager.loadedSceneCount; i++)
            {
                currentScenes.Add(EditorSceneManager.GetSceneAt(i));
            }

            foreach (var name in environments)
            {
                var scene = Path.Combine("Assets", "External", "Environments", name, $"{name}.{SceneExtension}");

                Scene s = EditorSceneManager.OpenScene(scene, OpenSceneMode.Additive);
                try
                {
                    Manifest?manifest = null;

                    foreach (GameObject root in s.GetRootGameObjects())
                    {
                        MapOrigin origin = root.GetComponentInChildren <MapOrigin>();
                        if (origin != null)
                        {
                            manifest = new Manifest
                            {
                                assetName    = name,
                                bundleGuid   = Guid.NewGuid().ToString(),
                                bundleFormat = BundleConfig.MapBundleFormatVersion,
                                description  = origin.Description,
                                licenseName  = origin.LicenseName,
                                authorName   = "",
                                authorUrl    = "",
                            };
                            break;
                        }
                    }

                    if (manifest.HasValue)
                    {
                        envManifests.Add(manifest.Value);
                    }
                    else
                    {
                        throw new Exception($"Build failed: MapOrigin on {name} not found. Please add a MapOrigin component.");
                    }
                }
                finally
                {
                    if (!currentScenes.Contains(s))
                    {
                        EditorSceneManager.CloseScene(s, true);
                    }
                }
            }

            foreach (var name in vehicles)
            {
                var         prefab = Path.Combine("Assets", "External", "Vehicles", name, $"{name}.{PrefabExtension}");
                VehicleInfo info   = AssetDatabase.LoadAssetAtPath <GameObject>(prefab).GetComponent <VehicleInfo>();
                if (info == null)
                {
                    throw new Exception($"Build failed: Vehicle info on {name} not found. Please add a VehicleInfo component and rebuild.");
                }

                var manifest = new Manifest
                {
                    assetName    = name,
                    bundleGuid   = Guid.NewGuid().ToString(),
                    bundleFormat = BundleConfig.VehicleBundleFormatVersion,
                    description  = info.Description,
                    licenseName  = info.LicenseName,
                    authorName   = "",
                    authorUrl    = "",
                };

                vehicleManifests.Add(manifest);
            }

            foreach (var manifest in envManifests)
            {
                try
                {
                    var sceneAsset = Path.Combine("Assets", "External", "Environments", manifest.assetName, $"{manifest.assetName}.{SceneExtension}");

                    var textureBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_environment_textures",
                        assetNames      = AssetDatabase.GetDependencies(sceneAsset).Where(a => a.EndsWith(".png") || a.EndsWith(".jpg")).ToArray(),
                    };

                    var windowsBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_environment_main_windows",
                        assetNames      = new[] { sceneAsset },
                    };

                    BuildPipeline.BuildAssetBundles(
                        folder,
                        new[] { textureBuild, windowsBuild },
                        BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode,
                        UnityEditor.BuildTarget.StandaloneWindows64);

                    var linuxBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_environment_main_linux",
                        assetNames      = new[] { sceneAsset },
                    };

                    BuildPipeline.BuildAssetBundles(
                        folder,
                        new[] { textureBuild, linuxBuild },
                        BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode,
                        UnityEditor.BuildTarget.StandaloneLinux64);

                    File.WriteAllText(Path.Combine(folder, "manifest"), new Serializer().Serialize(manifest));
                    try
                    {
                        using (ZipFile archive = ZipFile.Create(Path.Combine(folder, $"environment_{manifest.assetName}")))
                        {
                            archive.BeginUpdate();
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, textureBuild.assetBundleName)), textureBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, linuxBuild.assetBundleName)), linuxBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, windowsBuild.assetBundleName)), windowsBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, "manifest")), "manifest", CompressionMethod.Stored, true);
                            archive.CommitUpdate();
                            archive.Close();
                        }
                    }
                    finally
                    {
                        File.Delete(Path.Combine(folder, "manifest"));
                    }
                }
                finally
                {
                    var di = new DirectoryInfo(folder);

                    var files = di.GetFiles($"{manifest.bundleGuid}*");
                    Array.ForEach(files, f => f.Delete());

                    files = di.GetFiles($"AssetBundles*");
                    Array.ForEach(files, f => f.Delete());
                }
            }

            foreach (var manifest in vehicleManifests)
            {
                try
                {
                    var prefabAsset = Path.Combine("Assets", "External", "Vehicles", manifest.assetName, $"{manifest.assetName}.{PrefabExtension}");

                    var textureBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_vehicle_textures",
                        assetNames      = AssetDatabase.GetDependencies(prefabAsset).Where(a => a.EndsWith(".png") || a.EndsWith(".jpg")).ToArray()
                    };

                    var windowsBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_vehicle_main_windows",
                        assetNames      = new[] { prefabAsset },
                    };

                    BuildPipeline.BuildAssetBundles(
                        folder,
                        new[] { textureBuild, windowsBuild },
                        BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode,
                        UnityEditor.BuildTarget.StandaloneWindows64);

                    var linuxBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_vehicle_main_linux",
                        assetNames      = new[] { prefabAsset },
                    };

                    BuildPipeline.BuildAssetBundles(
                        folder,
                        new[] { textureBuild, linuxBuild },
                        BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode,
                        UnityEditor.BuildTarget.StandaloneLinux64);

                    File.WriteAllText(Path.Combine(folder, "manifest"), new Serializer().Serialize(manifest));
                    try
                    {
                        using (ZipFile archive = ZipFile.Create(Path.Combine(folder, $"vehicle_{manifest.assetName}")))
                        {
                            archive.BeginUpdate();
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, textureBuild.assetBundleName)), textureBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, linuxBuild.assetBundleName)), linuxBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, windowsBuild.assetBundleName)), windowsBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, "manifest")), "manifest", CompressionMethod.Stored, true);
                            archive.CommitUpdate();
                            archive.Close();
                        }
                    }
                    finally
                    {
                        File.Delete(Path.Combine(folder, "manifest"));
                    }
                }
                finally
                {
                    var di = new DirectoryInfo(folder);

                    var files = di.GetFiles($"{manifest.bundleGuid}*");
                    Array.ForEach(files, f => f.Delete());

                    files = di.GetFiles($"AssetBundles*");
                    Array.ForEach(files, f => f.Delete());
                }
            }
        }
Пример #58
0
        static void RunSensorsBuild(string outputFolder, List <string> sensors)
        {
            outputFolder = Path.Combine(outputFolder, "Sensors");
            Directory.CreateDirectory(outputFolder);

            var externalSensors = Path.Combine(Application.dataPath, "External", "Sensors");
            List <DirectoryInfo> directories = new List <DirectoryInfo>();

            foreach (var s in sensors)
            {
                directories.Add(new DirectoryInfo(Path.Combine(Application.dataPath, "External", "Sensors", s)));
            }

            var sensorsAsmDefPath = Path.Combine(externalSensors, "Simulator.Sensors.asmdef");
            var sensorsAsmDef     = JsonUtility.FromJson <AsmdefBody>(File.ReadAllText(sensorsAsmDefPath));

            foreach (var directoryInfo in directories)
            {
                string bundleGuid = Guid.NewGuid().ToString();
                string filename   = directoryInfo.Name;

                try
                {
                    var prefab = Path.Combine("Assets", "External", "Sensors", filename, $"{filename}.prefab");
                    if (!File.Exists(Path.Combine(Application.dataPath, "..", prefab)))
                    {
                        Debug.LogError($"Building of {filename} failed: {prefab} not found");
                        break;
                    }

                    AsmdefBody asmdefContents = new AsmdefBody();
                    asmdefContents.name       = filename;
                    asmdefContents.references = sensorsAsmDef.references;
                    File.WriteAllText(Path.Combine(externalSensors, filename, $"{filename}.asmdef"), JsonUtility.ToJson(asmdefContents));

                    Manifest manifest = new Manifest
                    {
                        assetName    = filename,
                        bundleGuid   = bundleGuid,
                        bundleFormat = BundleConfig.SensorBundleFormatVersion,
                        description  = "",
                        licenseName  = "",
                        authorName   = "",
                        authorUrl    = "",
                    };

                    var windowsBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{bundleGuid}_sensor_main_windows",
                        assetNames      = new[] { prefab },
                    };

                    BuildPipeline.BuildAssetBundles(
                        outputFolder,
                        new[] { windowsBuild },
                        BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode,
                        UnityEditor.BuildTarget.StandaloneWindows64);

                    if (!File.Exists(Path.Combine(outputFolder, windowsBuild.assetBundleName)))
                    {
                        Debug.LogError($"Failed to find Windows asset bundle of {filename}. Please correct other errors and try again.");
                        return;
                    }

                    var linuxBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{bundleGuid}_sensor_main_linux",
                        assetNames      = new[] { prefab },
                    };

                    BuildPipeline.BuildAssetBundles(
                        outputFolder,
                        new[] { linuxBuild },
                        BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode,
                        UnityEditor.BuildTarget.StandaloneLinux64);

                    if (!File.Exists(Path.Combine(outputFolder, linuxBuild.assetBundleName)))
                    {
                        Debug.LogError($"Failed to find Linux asset bundle of {filename}. Please correct other errors and try again.");
                        return;
                    }

                    DirectoryInfo prefabDir = new DirectoryInfo(Path.Combine(externalSensors, filename));
                    var           scripts   = prefabDir.GetFiles("*.cs", SearchOption.AllDirectories).Select(script => script.FullName).ToArray();

                    var outputAssembly  = Path.Combine(outputFolder, $"{filename}.dll");
                    var assemblyBuilder = new AssemblyBuilder(outputAssembly, scripts);

                    var assemblies = AppDomain.CurrentDomain.GetAssemblies();
                    var modules    = assemblies.Where(asm =>
                                                      asm.GetName().Name == "UnityEngine" ||
                                                      asm.GetName().Name == "UnityEngine.JSONSerializeModule" ||
                                                      asm.GetName().Name == "UnityEngine.CoreModule" ||
                                                      asm.GetName().Name == "UnityEngine.PhysicsModule").ToArray();

                    assemblyBuilder.additionalReferences = modules.Select(a => a.Location).ToArray();

                    assemblyBuilder.buildFinished += delegate(string assemblyPath, CompilerMessage[] compilerMessages)
                    {
                        var errorCount   = compilerMessages.Count(m => m.type == CompilerMessageType.Error);
                        var warningCount = compilerMessages.Count(m => m.type == CompilerMessageType.Warning);

                        try
                        {
                            Debug.Log($"Assembly build finished for {assemblyPath}");
                            if (errorCount != 0)
                            {
                                Debug.Log($"Found {errorCount} errors");

                                foreach (CompilerMessage message in compilerMessages)
                                {
                                    if (message.type == CompilerMessageType.Error)
                                    {
                                        Debug.LogError(message.message);
                                        return;
                                    }
                                }
                            }
                            else
                            {
                                var manifestOutput = Path.Combine(outputFolder, "manifest");
                                File.WriteAllText(manifestOutput, new Serializer().Serialize(manifest));

                                using (ZipFile archive = ZipFile.Create(Path.Combine(outputFolder, $"sensor_{filename}")))
                                {
                                    archive.BeginUpdate();
                                    archive.Add(new StaticDiskDataSource(Path.Combine(outputFolder, linuxBuild.assetBundleName)), linuxBuild.assetBundleName, CompressionMethod.Stored, true);
                                    archive.Add(new StaticDiskDataSource(Path.Combine(outputFolder, windowsBuild.assetBundleName)), windowsBuild.assetBundleName, CompressionMethod.Stored, true);
                                    archive.Add(new StaticDiskDataSource(outputAssembly), $"{filename}.dll", CompressionMethod.Stored, true);
                                    archive.Add(new StaticDiskDataSource(manifestOutput), "manifest", CompressionMethod.Stored, true);
                                    archive.CommitUpdate();
                                    archive.Close();
                                }
                            }
                        }
                        finally
                        {
                            var di = new DirectoryInfo(outputFolder);
                            SilentDelete(Path.Combine(outputFolder, $"{filename}.dll"));
                            SilentDelete(Path.Combine(outputFolder, $"{filename}.pdb"));
                            SilentDelete(Path.Combine(outputFolder, "manifest"));
                        }
                    };

                    // Start build of assembly
                    if (!assemblyBuilder.Build())
                    {
                        Debug.LogErrorFormat("Failed to start build of assembly {0}!", assemblyBuilder.assemblyPath);
                        return;
                    }

                    while (assemblyBuilder.status != AssemblyBuilderStatus.Finished)
                    {
                    }
                }
                finally
                {
                    var di = new DirectoryInfo(outputFolder);

                    var files = di.GetFiles($"{bundleGuid}*");
                    Array.ForEach(files, f => SilentDelete(f.FullName));

                    SilentDelete(Path.Combine(outputFolder, "Sensors"));
                    SilentDelete(Path.Combine(outputFolder, "Sensors.manifest"));

                    SilentDelete(Path.Combine(externalSensors, filename, $"{filename}.asmdef"));
                    SilentDelete(Path.Combine(externalSensors, filename, $"{filename}.asmdef.meta"));
                }
            }
        }
        #pragma warning restore IDE0051
        #endregion

        private void SaveAvatar(AvatarDescriptor avatar)
        {
            string destinationPath = EditorUtility.SaveFilePanel("Save avatar file", null, avatar.name + ".avatar", "avatar");

            if (string.IsNullOrEmpty(destinationPath))
            {
                return;
            }

            string destinationFileName = Path.GetFileName(destinationPath);
            string tempFolder          = Application.temporaryCachePath;
            string prefabPath          = Path.Combine("Assets", "_CustomAvatar.prefab");

            PrefabUtility.SaveAsPrefabAsset(avatar.gameObject, prefabPath);

            AssetBundleBuild assetBundleBuild = new AssetBundleBuild
            {
                assetBundleName = destinationFileName,
                assetNames      = new[]   {
                    prefabPath
                }
            };

            assetBundleBuild.assetBundleName = destinationFileName;

            BuildTargetGroup selectedBuildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;
            BuildTarget      activeBuildTarget        = EditorUserBuildSettings.activeBuildTarget;

            AssetBundleManifest manifest = BuildPipeline.BuildAssetBundles(tempFolder, new[] { assetBundleBuild }, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);

            // switch back to what it was before creating the asset bundle
            EditorUserBuildSettings.SwitchActiveBuildTarget(selectedBuildTargetGroup, activeBuildTarget);

            if (manifest != null)
            {
                string tempAssetBundlePath = Path.Combine(tempFolder, destinationFileName);

                if (!File.Exists(tempAssetBundlePath))
                {
                    // Unity on Linux saves to a lowercase file name for some reason
                    tempAssetBundlePath = Path.Combine(tempFolder, destinationFileName.ToLower());
                }

                try
                {
                    File.Copy(tempAssetBundlePath, destinationPath, true);

                    EditorUtility.DisplayDialog("Export Successful!", $"{avatar.name} was exported successfully!", "OK");
                }
                catch (IOException ex)
                {
                    Debug.LogError(ex);

                    EditorUtility.DisplayDialog("Export Failed", $"Could not copy avatar to selected folder. Please check the Unity console for more information.", "OK");
                }
            }
            else
            {
                EditorUtility.DisplayDialog("Export Failed", "Failed to create asset bundle! Please check the Unity console for more information.", "OK");
            }

            AssetDatabase.DeleteAsset(prefabPath);
            AssetDatabase.Refresh();
        }
    // Build assets that are used by scenes from the given list.
    // This function will automatically de-duplicated same asset file being referenced in multiple scenes.
    // Scene bundles will be created with name pattern: <SceneName>_<AssetTypeExtention><ChunckNumber>
    private static void BuildSceneBundles(List <OVRBundleTool.EditorSceneInfo> sceneList)
    {
        DateTime totalStart = DateTime.Now;
        // Keeps track of dependent assets across scenes
        // to ensure each asset is only packaged once in one of the scene bundles.
        // uniqueAssetInSceneBundle is a map from "asset unique identifier" to the first scene that references the asset.
        // It supports different assets with same file name as "asset unique identifier" contain full qualified asset file path
        Dictionary <string, string> uniqueAssetInSceneBundle = new Dictionary <string, string>();

        // List of bundle targets for Unity's build pipeline to package
        List <AssetBundleBuild> assetBundleBuilds = new List <AssetBundleBuild>();
        // Map that contains "asset type" to list of assets that are of the asset type
        Dictionary <string, List <string> > extToAssetList = new Dictionary <string, List <string> >();

        // Check if assets in Resources need to be packaged
        if (CheckForResources())
        {
            var resourceDirectories = Directory.GetDirectories("Assets", "Resources", SearchOption.AllDirectories).ToArray();
            // Fetch a list of all files in resource directory
            string[] resourceAssetPaths = AssetDatabase.FindAssets("", resourceDirectories).Select(x => AssetDatabase.GUIDToAssetPath(x)).ToArray();
            ProcessAssets(resourceAssetPaths, "resources", ref uniqueAssetInSceneBundle, ref extToAssetList);

            AssetBundleBuild resourceBundle = new AssetBundleBuild();
            resourceBundle.assetNames      = uniqueAssetInSceneBundle.Keys.ToArray();
            resourceBundle.assetBundleName = OVRSceneLoader.resourceBundleName;
            assetBundleBuilds.Add(resourceBundle);
        }

        // Create scene bundle output directory
        string sceneBundleDirectory = Path.Combine(BUNDLE_MANAGER_OUTPUT_PATH, BUNDLE_MANAGER_MASTER_BUNDLE);

        if (!Directory.Exists(sceneBundleDirectory))
        {
            Directory.CreateDirectory(sceneBundleDirectory);
        }

        OVRBundleTool.PrintLog("Building scene bundles . . . ");
        DateTime labelingStart = DateTime.Now;

        foreach (var scene in sceneList)
        {
            // Get all the assets that the scene depends on and sort them by type
            DateTime getDepStart       = DateTime.Now;
            string[] assetDependencies = AssetDatabase.GetDependencies(scene.scenePath);
            Debug.Log("[OVRBundleManager] - " + scene.sceneName + " - Calculated scene asset dependencies in: " + (DateTime.Now - getDepStart).TotalSeconds);
            ProcessAssets(assetDependencies, scene.sceneName, ref uniqueAssetInSceneBundle, ref extToAssetList);

            // Add the scene into it's own bundle
            string[] sceneAsset = new string[1] {
                scene.scenePath
            };
            AssetBundleBuild sceneBuild = new AssetBundleBuild();
            sceneBuild.assetBundleName = "scene_" + scene.sceneName;
            sceneBuild.assetNames      = sceneAsset;
            assetBundleBuilds.Add(sceneBuild);
        }

        // Chunk the asset bundles by number of assets
        foreach (string ext in extToAssetList.Keys)
        {
            int assetCount = extToAssetList[ext].Count;
            int numChunks  = (assetCount + BUNDLE_CHUNK_SIZE - 1) / BUNDLE_CHUNK_SIZE;
            //Debug.Log(ext + " has " + assetCount + " asset(s) that will be split into " + numChunks + " chunk(s)");
            for (int i = 0; i < numChunks; i++)
            {
                List <string> assetChunkList;
                if (i == numChunks - 1)
                {
                    int size = BUNDLE_CHUNK_SIZE - (numChunks * BUNDLE_CHUNK_SIZE - assetCount);
                    assetChunkList = extToAssetList[ext].GetRange(i * BUNDLE_CHUNK_SIZE, size);
                }
                else
                {
                    assetChunkList = extToAssetList[ext].GetRange(i * BUNDLE_CHUNK_SIZE, BUNDLE_CHUNK_SIZE);
                }
                AssetBundleBuild build = new AssetBundleBuild();
                build.assetBundleName = "asset_" + ext + i;
                build.assetNames      = assetChunkList.ToArray();
                //Debug.Log("Chunk " + i + " has " + assetChunkList.Count + " asset(s)");
                assetBundleBuilds.Add(build);
            }
        }

        Debug.Log("[OVRBundleManager] - Created chucked scene bundles in: " + (DateTime.Now - labelingStart).TotalSeconds);

        // Build asset bundles
        BuildPipeline.BuildAssetBundles(sceneBundleDirectory, assetBundleBuilds.ToArray(),
                                        BuildAssetBundleOptions.UncompressedAssetBundle, BuildTarget.Android);

        double bundleBuildTime = (DateTime.Now - totalStart).TotalSeconds;

        Debug.Log("[OVRBundleManager] - Total Time: " + bundleBuildTime);
        OVRPlugin.SendEvent("oculus_bundle_tool", "bundle_build_time", bundleBuildTime.ToString());
    }