static bool LuaToByteCode(string sSrcFileDir, string sDstFileDir, string sGroupName, string[] includePath)
    {
        bool bJITExists = File.Exists(ms_sLuaJitToolPath);

        if (!bJITExists || !Directory.Exists(sSrcFileDir))
        {
            string sJitErr = "no File:" + ms_sLuaJitToolPath;
            string sLuaErr = "no Path:" + sSrcFileDir;
            Debug.LogError(bJITExists ? sLuaErr : sJitErr);
            return(false);
        }

        //Debug.Log(sGroupName + ": Lua To CodeByte Start!");
        bool bSuccess = true;

        System.DateTime now = System.DateTime.Now;

        if (Directory.Exists(sDstFileDir))
        {
            Directory.Delete(sDstFileDir, true);
        }
        Directory.CreateDirectory(sDstFileDir);

        /*string sLuaCsvTmp = Application.dataPath + "/../../LuaCsvBytes/" + sGroupName + "/";
         * //Debug.Log("LuaCsvTmp:" + sLuaCsvTmp);
         *
         * if (Directory.Exists(sLuaCsvTmp))
         *  Directory.Delete(sLuaCsvTmp, true);
         * Directory.CreateDirectory(sLuaCsvTmp);*/

        string[] sDirs     = { sSrcFileDir };
        string[] sPatterns = { "*.lua", "*.csv" };
        string[] sFiles    = AppPackage.GetFiles(sDirs, sPatterns, false);
        int      nCount    = sFiles.Length;

        for (int i = 0; i < nCount; i++)
        {
            if (!IsInlcudePath(sFiles[i], includePath))
            {
                continue;
            }

            // 客户端要支持IOS的arm64,所以直接使用源码
            string sFilePath = sFiles[i].Replace("\\", "/");
            string sFileName = sFilePath.Substring(sSrcFileDir.Length).Replace('/', '.') + ".bytes";
            string sDstFile  = sDstFileDir + "/" + sFileName;
            File.Copy(sFilePath, sDstFile, true);


            /*// 服务端使用luajit,lua文件编译成字节码,csv文件直接拷贝
             * string sLSFile = sLuaCsvTmp + sFilePath.Substring(sSrcFileDir.Length);
             * string sBCDir = sLSFile.Substring(0, sLSFile.LastIndexOf('/'));
             * if (!Directory.Exists(sBCDir))
             *  Directory.CreateDirectory(sBCDir);
             *
             * if (sFilePath.EndsWith(".lua"))
             * {
             *  // 调用luajit.exe进程打包Lua文件。1、检查lua代码的语法;2、正式服务端不能使用源码
             *  System.Diagnostics.Process p = new System.Diagnostics.Process();
             *  p.StartInfo.FileName = ms_sLuaJitToolPath;
             *  p.StartInfo.Arguments = " -bg " + sFilePath + " " + sLSFile;//LuaJIT的命令 //p.StartInfo.Arguments = " -o " + sDstFile + " " + sFilePath; //LuaC的命令
             *  p.StartInfo.UseShellExecute = false;
             *  p.StartInfo.RedirectStandardInput = true;
             *  p.StartInfo.RedirectStandardOutput = true;
             *  p.StartInfo.RedirectStandardError = true;
             *  p.StartInfo.CreateNoWindow = true;
             *
             *  // p.Exited += (object sender, System.EventArgs e) => { p.Close(); };
             *  p.Start();
             *  string sErrInfo = p.StandardError.ReadToEnd();
             *  // string sOutInfo = p.StandardOutput.ReadToEnd();
             *  // p.StandardInput.WriteLine("exit");
             *  p.WaitForExit();
             *  p.Close();
             *
             *  if (sErrInfo != null && sErrInfo != "")
             *  {
             *      bSuccess = false;
             *      Debug.LogError(sErrInfo);
             *  }
             * }
             * else
             * {
             *  File.Copy(sFilePath, sLSFile, true);
             * }*/

            float fProgress = i * 1.0f / nCount;
            EditorUtility.DisplayProgressBar("LuaCsv CodeByte", sFilePath + ": " + fProgress.ToString(), fProgress);
            // Debug.Log(sFilePath + " => " + sDstFile);
        }

        EditorUtility.ClearProgressBar();
        System.GC.Collect();

        System.TimeSpan disTime = System.DateTime.Now - now;
        Debug.Log(sSrcFileDir + ": " + nCount.ToString() + " Files To ByteCode! Cost " + (disTime.Hours * 3600 + disTime.Minutes * 60 + disTime.Seconds).ToString());

        return(bSuccess);
    }
示例#2
0
 private void OnBuildAssetBundlesError(string errorMessage)
 {
     EditorUtility.ClearProgressBar();
     Debug.LogWarning(Utility.Text.Format("Build AssetBundles error with error message '{0}'.", errorMessage));
 }
        void InitializeAllActiveConverters(ClickEvent evt)
        {
            // If we use search index, go async
            if (ShouldCreateSearchIndex())
            {
                CreateSearchIndex(m_URPConverterIndex);
            }
            // Otherwise do everything directly
            else
            {
                ConverterCollectData(() => { EditorUtility.ClearProgressBar(); });
            }

            void CreateSearchIndex(string name)
            {
                // Create <guid>.index in the project
                var title = $"Building {name} search index";
                EditorUtility.DisplayProgressBar(title, "Creating search index...", -1f);

                // Private implementation of a file naming function which puts the file at the selected path.
                Type assetdatabase = typeof(AssetDatabase);
                var indexPath = (string)assetdatabase.GetMethod("GetUniquePathNameAtSelectedPath", BindingFlags.NonPublic | BindingFlags.Static).Invoke(assetdatabase, new object[] { name });

                // Write search index manifest
                System.IO.File.WriteAllText(indexPath,
            @"{
                ""roots"": [""Assets""],
                ""includes"": [],
                ""excludes"": [],
                ""options"": {
                    ""types"": true,
                    ""properties"": true,
                    ""extended"": true,
                    ""dependencies"": true
                    },
                ""baseScore"": 9999
                }");

                // Import the search index
                AssetDatabase.ImportAsset(indexPath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.DontDownloadFromCacheServer);

                EditorApplication.delayCall += () =>
                {
                    // Create dummy request to ensure indexing has finished
                    var context = Search.SearchService.CreateContext("asset", $"p: a=\"{name}\"");
                    Search.SearchService.Request(context, (_, items) =>
                    {
                        OnSearchIndexCreated(name, indexPath, () =>
                        {
                            DeleteSearchIndex(context, indexPath);
                        });
                    });
                };
            }

            void OnSearchIndexCreated(string name, string path, Action onComplete)
            {
                EditorUtility.ClearProgressBar();

                ConverterCollectData(onComplete);
            }

            void ConverterCollectData(Action onConverterDataCollectionComplete)
            {
                EditorUtility.DisplayProgressBar($"Initializing converters", $"Initializing converters...", -1f);

                int convertersToConvert = 0;
                for (int i = 0; i < m_ConverterStates.Count; ++i)
                {
                    if (m_ConverterStates[i].requiresInitialization)
                    {
                        convertersToConvert++;
                        GetAndSetData(i, onConverterDataCollectionComplete);
                    }
                }

                // If we did not kick off any converter intialization
                // We can complete everything immediately
                if (convertersToConvert == 0)
                {
                    onConverterDataCollectionComplete?.Invoke();
                }
            }

            void DeleteSearchIndex(SearchContext context, string indexPath)
            {
                context?.Dispose();
                // Client code has finished with the created index. We can delete it.
                AssetDatabase.DeleteAsset(indexPath);
                EditorUtility.ClearProgressBar();
            }
        }
    static public Shader Compile(TCP2_Config config, Shader existingShader, TCP2_ShaderGenerator.ShaderGeneratorTemplate template, float progress, bool overwritePrompt)
    {
        //UI
        if (progress >= 0f)
        {
            EditorUtility.DisplayProgressBar("Hold On", "Generating Shader: " + config.ShaderName, progress);
        }

        //Generate source
        string source = config.GenerateShaderSource(template, existingShader);

        if (string.IsNullOrEmpty(source))
        {
            Debug.LogError("[TCP2 Shader Generator] Can't save Shader: source is null or empty!");
            return(null);
        }

        //Save to disk
        Shader shader = SaveShader(config, existingShader, source, overwritePrompt, config.isModifiedExternally);

        if (config.configType == "terrain")
        {
            //Generate Base shader
            TCP2_Config baseConfig = config.Copy();
            baseConfig.Filename   = baseConfig.Filename + "_Base";
            baseConfig.ShaderName = "Hidden/" + baseConfig.ShaderName + "-Base";
            baseConfig.Features.Add("TERRAIN_BASE");

            source = baseConfig.GenerateShaderSource(template, existingShader);
            if (string.IsNullOrEmpty(source))
            {
                Debug.LogError("[TCP2 Shader Generator] Can't save Terrain Base Shader: source is null or empty!");
            }
            else
            {
                SaveShader(baseConfig, existingShader, source, false, false);
            }

            //Generate AddPass shader
            TCP2_Config addPassConfig = config.Copy();
            addPassConfig.Filename   = addPassConfig.Filename + "_AddPass";
            addPassConfig.ShaderName = "Hidden/" + addPassConfig.ShaderName + "-AddPass";
            addPassConfig.Features.Add("TERRAIN_ADDPASS");
            addPassConfig.Flags.Add("decal:add");

            source = addPassConfig.GenerateShaderSource(template, existingShader);
            if (string.IsNullOrEmpty(source))
            {
                Debug.LogError("[TCP2 Shader Generator] Can't save Terrain AddPass Shader: source is null or empty!");
            }
            else
            {
                SaveShader(addPassConfig, existingShader, source, false, false);
            }
        }

        //UI
        if (progress >= 0f)
        {
            EditorUtility.ClearProgressBar();
        }

        return(shader);
    }
示例#5
0
 private void OnAnalyzeCompleted()
 {
     EditorUtility.ClearProgressBar();
 }
示例#6
0
    /// <summary>
    /// Update the sprite atlas, keeping only the sprites that are on the specified list.
    /// </summary>

    static public void UpdateAtlas(INGUIAtlas obj, List <SpriteEntry> sprites)
    {
#if UNITY_2018_3_OR_NEWER
        // Contributed by B9 from https://discord.gg/tasharen
        if (obj is UIAtlas)         // Prefab-based atlas
        {
            Debug.LogWarning("Updating a legacy atlas: issues may occur. Please update the atlas to a new format that uses Scriptable Objects rather than Prefabs.", obj as Object);
            var atlas = (obj as UIAtlas);

            if (!PrefabUtility.IsPartOfPrefabAsset(atlas.gameObject))
            {
                Debug.LogWarning("Atlas is not sourced from prefab asset, ignoring the request to update it");
                return;
            }

            var assetPath = AssetDatabase.GetAssetPath(atlas.gameObject);

            if (string.IsNullOrEmpty(assetPath))
            {
                Debug.LogWarning("Atlas asset path could not be found, aborting");
                return;
            }

            var assetRoot = PrefabUtility.LoadPrefabContents(assetPath);
            var atlasTemp = assetRoot.GetComponent <UIAtlas>();

            if (atlasTemp == null)
            {
                Debug.LogWarning("Atlas component could not be found in the loaded prefab, aborting");
                PrefabUtility.UnloadPrefabContents(assetRoot);
                return;
            }

            if (sprites.Count > 0)
            {
                // Combine all sprites into a single texture and save it
                if (UpdateTexture(atlasTemp, sprites))
                {
                    // Replace the sprites within the atlas
                    ReplaceSprites(atlasTemp, sprites);
                }

                // Release the temporary textures
                ReleaseSprites(sprites);
            }
            else
            {
                atlasTemp.spriteList.Clear();
                var texturePath = NGUIEditorTools.GetSaveableTexturePath(atlasTemp);
                atlasTemp.spriteMaterial.mainTexture = null;
                if (!string.IsNullOrEmpty(texturePath))
                {
                    AssetDatabase.DeleteAsset(texturePath);
                }
            }

            PrefabUtility.SaveAsPrefabAsset(assetRoot, assetPath);
            Selection.activeObject = NGUISettings.atlas as Object;
            EditorUtility.ClearProgressBar();

            PrefabUtility.UnloadPrefabContents(assetRoot);
            AssetDatabase.Refresh();

            var assetUpdated = (GameObject)AssetDatabase.LoadMainAssetAtPath(assetPath);
            var newAtlas     = assetUpdated.GetComponent <UIAtlas>();
            NGUISettings.atlas = newAtlas;
            newAtlas.MarkAsChanged();

            var panels = NGUITools.FindActive <UIPanel>();

            foreach (var panel in panels)
            {
                if (!panel.enabled)
                {
                    continue;
                }
                panel.enabled = false;
                panel.enabled = true;
            }
            EditorUtility.CollectDependencies(panels);
            return;
        }
#endif
        if (sprites.Count > 0)
        {
            // Combine all sprites into a single texture and save it
            if (UpdateTexture(obj, sprites))
            {
                ReplaceSprites(obj, sprites);
            }
            ReleaseSprites(sprites);
        }
        else
        {
            obj.spriteList.Clear();
            var path = NGUIEditorTools.GetSaveableTexturePath(obj);
            obj.spriteMaterial.mainTexture = null;
            if (!string.IsNullOrEmpty(path))
            {
                AssetDatabase.DeleteAsset(path);
            }
            obj.MarkAsChanged();
        }

        EditorUtility.ClearProgressBar();
    }
示例#7
0
        internal static AssetHunterBuildReport AnalyzeBuildLog()
        {
            AssetHunterBuildReport buildReport = new AssetHunterBuildReport();
            string UnityEditorLogfile          = GetLogFolderPath();

            try
            {
                // Have to use FileStream to get around sharing violations!
                FileStream   FS = new FileStream(UnityEditorLogfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader SR = new StreamReader(FS);

                string line;
                int    linesRead = 0;
                int    lineIndex = 0;

                while (!SR.EndOfStream)
                {
                    line = SR.ReadLine();
                    linesRead++;
                    if ((line).Contains("Mono dependencies included in the build"))
                    {
                        lineIndex = linesRead;
                    }
                }

                FS.Position = 0;
                SR.DiscardBufferedData();

                //Start reading from log at the right line
                for (int i = 0; i < lineIndex - 1; i++)
                {
                    SR.ReadLine();
                }

                while (!SR.EndOfStream && !(line = SR.ReadLine()).Contains("Mono dependencies included in the build"))
                {
                    ;
                }
                while (!SR.EndOfStream && (line = SR.ReadLine()) != "")
                {
                    int stringLength = line.Length;
                    int startIndex   = line.LastIndexOf(" ");
                    buildReport.AddDependency(line.Substring(startIndex, stringLength - startIndex));
                }
                while (!SR.EndOfStream && !(line = SR.ReadLine()).Contains("Used Assets"))
                {
                    ;
                }
                bool assetAnalysisComplete = false;
                while (!SR.EndOfStream && !assetAnalysisComplete)
                {
                    string curLine = SR.ReadLine();

                    if (curLine == "" || curLine.Contains("System memory in use before") || !curLine.Contains("% "))
                    {
                        assetAnalysisComplete = true;
                    }
                    else
                    {
                        if (!curLine.Contains("Built-in"))
                        {
                            string str = curLine.Substring(curLine.IndexOf("% ") + 2);
                            if (str.StartsWith("assets/", true, null))
                            {
                                EditorUtility.DisplayProgressBar(
                                    "Parsing build log",
                                    "Parsing build log to retrieve info",
                                    (float)SR.BaseStream.Position / (float)SR.BaseStream.Length);

                                UnityEngine.Object obj = UnityEditor.AssetDatabase.LoadAssetAtPath(str, typeof(UnityEngine.Object));

                                if (obj != null)
                                {
                                    BuildReportAsset asset = new BuildReportAsset();

                                    asset.SetAssetInfo(obj, str);
                                    //Split on whitespace
                                    string[] splitstring = curLine.Split(null);
                                    asset.SetSize(float.Parse(splitstring[1]), splitstring[2]);
                                    buildReport.AddAsset(asset);
                                }
                                else
                                {
                                    Debug.Log(str + " does not seem to be a valid asset (Maybe its a \"terrain folder\"");
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception E)
            {
                Debug.LogError("Error: " + E);
            }
            EditorUtility.ClearProgressBar();

            return(buildReport);
        }
示例#8
0
        static HashSet <string> GetUnreferencedAssets()
        {
            var referencesOutsideResources = new HashSet <string>();
            var otherAssets = new HashSet <string>();

            var ignoreExtensions = new HashSet <string>(new [] {
                ".asset",
                ".prefs",
                ".cs",
                ".boo",
                ".js",
                ".rsp",
                ".m",
                ".mm",
                ".py",
                ".h",
                ".plist",
                ".a",
                ".dll",
                ".pyc",
                ".scpt",
                ".userprefs",
                ".jar",
                ".json",
                ".zip",
                ".xib",
                ".c",
                ".o",
                ".patch",
                ".icns",
                ""
            });

            var   assets      = AssetDatabase.GetAllAssetPaths().Where(file => !ignoreExtensions.Contains(Path.GetExtension(file).ToLower())).ToArray();
            int   total       = assets.Length;
            float invTotal    = 1.0f / total;
            int   count       = 0;
            var   totalString = " / " + total;

            foreach (var asset in assets)
            {
                if (count % 20 == 0 && EditorUtility.DisplayCancelableProgressBar("Find Unreferenced Asset(s)", "Processing... " + count + totalString, (count * invTotal)))
                {
                    break;
                }
                if (IsResourceOrScene(asset))
                {
                    var dependencies = AssetDatabase.GetDependencies(new [] { asset })
                                       .Where(dependency => !dependency.StartsWith("Assets/Resources") && dependency != asset);
                    referencesOutsideResources.UnionWith(dependencies);
                }
                else
                {
                    otherAssets.Add(asset);
                }
            }

            otherAssets.ExceptWith(referencesOutsideResources);
            otherAssets.ExceptWith(LibraryReferences());
            EditorUtility.ClearProgressBar();

            return(otherAssets);
        }
示例#9
0
        public static void GenerateStorageFactory()
        {
            EditorUtility.DisplayProgressBar(PB_TITLE, "Setup", 0.1f);

            Dictionary <Type, (ulong id, Assembly assembly)> typeToId = new Dictionary <Type, (ulong id, Assembly assembly)>();
            ulong idMilestone = 0;

            if (File.Exists(GetPathFull()))
            {
                #region Identifying already registered types / ids

                ulong?   holdingID           = null;
                Assembly currentTypeAssembly = null;

                EditorUtility.DisplayProgressBar(PB_TITLE, $"Reading existing {STORAGE_OBJECT_FACTORY_FILE_NAME}", 0.3f);

                foreach (string line in File.ReadLines(GetPathFull()))
                {
                    string   trimmedLine = line.Trim();
                    string[] varToAssignmentSplitItems = trimmedLine.Split(Consts.ASSIGN_CHAR);

                    // Assignment of variable identified
                    if (varToAssignmentSplitItems.Length == 2)
                    {
                        string   varName         = varToAssignmentSplitItems[0].Trim();
                        string[] varNameSections = varName.Split(' ');
                        varName = varNameSections[varNameSections.Length - 1];

                        string varValue = varToAssignmentSplitItems[1].Trim(';');

                        if (varName == Consts.CONST_NAME_ID_MILESTONE)
                        {
                            idMilestone = ulong.Parse(varValue);
                        }
                    }

                    if (!holdingID.HasValue)
                    {
                        // Identify case ID
                        if (trimmedLine.StartsWith(Consts.CASE_START) && trimmedLine.EndsWith(Consts.CASE_END))
                        {
                            string idString = trimmedLine.Remove(0, Consts.CASE_START.Length);
                            idString  = idString.Remove(idString.IndexOf(Consts.CASE_END), 1);
                            holdingID = ulong.Parse(idString);
                            continue;
                        }
                    }
                    else
                    {
                        // Identify Assembly (before identifying type)
                        if (currentTypeAssembly == null)
                        {
                            if (trimmedLine.StartsWith(Consts.COMMENT_STRING))
                            {
                                string assemblyStringValue = trimmedLine.Remove(0, Consts.COMMENT_STRING.Length).Trim();
                                if (assemblyStringValue.StartsWith(Consts.ASSEMBLY_PREFIX))
                                {
                                    assemblyStringValue = assemblyStringValue.Remove(0, Consts.ASSEMBLY_PREFIX.Length).Trim();
                                    try
                                    {
                                        currentTypeAssembly = Assembly.Load(assemblyStringValue);
                                    }
                                    catch
                                    {
                                        Debug.LogError($"Could not load Assembly {assemblyStringValue} for ID {holdingID.Value}");
                                        holdingID = null;
                                    }
                                }
                            }
                        }
                        else
                        {
                            // Identify class type (after assembly identification)
                            if (trimmedLine.Contains(Consts.ASSIGN_NEW))
                            {
                                string[] classAssignItems  = trimmedLine.Split(new string[] { Consts.ASSIGN_NEW }, StringSplitOptions.None);
                                string   className         = classAssignItems[1];
                                int      endClassNameIndex = className.IndexOf('(');
                                className = className.Remove(endClassNameIndex, className.Length - endClassNameIndex).Trim();

                                try
                                {
                                    Type classType = currentTypeAssembly.GetType(className, true);
                                    typeToId.Add(classType, (holdingID.Value, currentTypeAssembly));
                                }
                                catch
                                {
                                    Debug.LogError($"Could not create type from ClassName {className} inside assembly {currentTypeAssembly.FullName}");
                                }
                            }

                            // Refresh Data for case
                            currentTypeAssembly = null;
                            holdingID           = null;
                        }
                    }
                }
                #endregion
            }
            else if (!Directory.Exists(GetPathBase()))
            {
                EditorUtility.DisplayProgressBar(PB_TITLE, "Creating directory for new Factory file", 0.3f);

                Directory.CreateDirectory(GetPathBase());
            }

            #region Get New Storage Type -> Ids for factory

            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            ulong      newCount   = 0;

            EditorUtility.DisplayProgressBar(PB_TITLE, $"Finding new {nameof(ISaveable)} classes for {STORAGE_OBJECT_FACTORY_FILE_NAME}", 0.5f);

            for (int i = 0; i < assemblies.Length; i++)
            {
                Assembly assembly         = assemblies[i];
                Type[]   newSaveableTypes = assembly.GetTypes().Where(x => typeof(ISaveable).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract).Where(x => !typeToId.ContainsKey(x)).ToArray();

                for (int j = 0; j < newSaveableTypes.Length; j++)
                {
                    Type newSaveableType = newSaveableTypes[j];

                    if (HasLoaderConstructor(newSaveableType) || typeof(ISaveableLoad).IsAssignableFrom(newSaveableType))
                    {
                        typeToId.Add(newSaveableType, (idMilestone, newSaveableType.Assembly));
                        idMilestone++;
                        newCount++;
                    }
                }
            }

            #endregion


            EditorUtility.DisplayProgressBar(PB_TITLE, $"Creating new {STORAGE_OBJECT_FACTORY_FILE_NAME} content", 0.8f);

            StringBuilder classBuilder = new StringBuilder();

            foreach (string line in File.ReadLines(GetTemplatePathFull()))
            {
                string        trimmedLine = line.Trim();
                string[]      varToAssignmentSplitItems = trimmedLine.Split(Consts.ASSIGN_CHAR);
                StringBuilder lineStringBuilder         = new StringBuilder();

                if (line.Contains(Consts.TEMPLATE_ID_MILESTONE_VALUE_INSERT_FIELD_ID))
                {
                    lineStringBuilder.AppendLine(line.Replace(Consts.TEMPLATE_ID_MILESTONE_VALUE_INSERT_FIELD_ID, idMilestone.ToString(CultureInfo.InvariantCulture)));
                }
                else if (line.Contains(Consts.TEMPLATE_TYPE_TO_ID_MAP_ITEMS_ID))
                {
                    foreach (var switchItemPair in typeToId)
                    {
                        lineStringBuilder.Append(Consts.Tabs(3));
                        lineStringBuilder.AppendLine(Consts.ToDictionaryItem(Consts.TypeToTypeOfString(switchItemPair.Key), Consts.ULongToString(switchItemPair.Value.id)));
                    }
                }
                else if (trimmedLine == Consts.TEMPLATE_SWITCH_CASE_INSERT_FIELD_ID)
                {
                    foreach (var switchItemPair in typeToId)
                    {
                        string variableName = $"value{switchItemPair.Value.id}";

                        lineStringBuilder.AppendLine($"{Consts.Tabs(4)} case {switchItemPair.Value.id}:");
                        lineStringBuilder.AppendLine($"{Consts.Tabs(5)} {Consts.COMMENT_ASSEMBLY_PREFIX} {switchItemPair.Value.assembly.FullName}:");

                        bool isConstructorLoader = HasLoaderConstructor(switchItemPair.Key);

                        lineStringBuilder.AppendLine($"{Consts.Tabs(5)} {(isConstructorLoader ? Consts.SAVEABLE_TYPE : Consts.SAVEABLE_WITHOUT_PARAM_TYPE)} {variableName} {Consts.ASSIGN_CHAR} {Consts.NEW} {switchItemPair.Key.FullName}({(isConstructorLoader ? Consts.PARAM_LOADER : string.Empty)});");

                        if (!isConstructorLoader)
                        {
                            lineStringBuilder.AppendLine($"{Consts.Tabs(5)} {variableName}.{nameof(ISaveableLoad.Load)}({Consts.PARAM_LOADER});");
                        }

                        lineStringBuilder.AppendLine($"{Consts.Tabs(5)} {Consts.RETURN} {variableName};");
                    }
                }
                else
                {
                    lineStringBuilder.AppendLine(line);
                }

                classBuilder.Append(lineStringBuilder.ToString());
            }

            EditorUtility.DisplayProgressBar(PB_TITLE, $"Creating new {STORAGE_OBJECT_FACTORY_FILE_NAME} file", 0.8f);

            File.WriteAllText(GetPathFull(), classBuilder.ToString());
            AssetDatabase.Refresh();
            EditorUtility.ClearProgressBar();

            // Highlight Asset
            TextAsset asset = AssetDatabase.LoadAssetAtPath <TextAsset>(GetPathFull());
            Selection.activeObject = asset;
            EditorGUIUtility.PingObject(asset);
        }
示例#10
0
        IEnumerator GenerateHLOD(GameObject[] gameObjects = null, Action <GameObject, GameObject> endCall = null)
        {
            m_CoroutineQueue.Enqueue(UpdateOctreeByLodGroup(gameObjects));

            s_endCall = endCall;

            yield return(MonoBehaviourHelper.StartCoroutine(m_CoroutineQueue.Dequeue()));

            while (m_RootVolume == null)
            {
                yield return(null);
            }

            #if UNITY_EDITOR
            if (m_RootVolume && m_RootVolume.dirty)
            {
                GameObject hlods = null;
                if (m_CurrHLODGenerate != null)//更新
                {
                    hlods = m_CurrHLODGenerate.m_HLODS;
                }
                if (!hlods)//创建
                {
                    hlods = new GameObject("RootHLOD");
                }

                m_CoroutineQueue.Enqueue(m_RootVolume.CheckAfterBVHUpdata(m_CurrHLODGenerate.m_BVHDivide.m_MaximunLayer));
                m_CoroutineQueue.Enqueue(m_RootVolume.UpdateHLODs(m_CurrHLODGenerate.m_BVHDivide.m_MaximunLayer, hlods));


                m_CoroutineQueue.Enqueue(m_RootVolume.UpdateRootVolume((List <LODVolume> backList) => {
                    HLODCull hlodCull = m_RootVolume.GetComponent <HLODCull>();
                    if (!m_RootVolume.GetComponent <HLODCull>())
                    {
                        hlodCull = m_RootVolume.gameObject.AddComponent <HLODCull>();
                        Selection.activeGameObject = hlodCull.gameObject;
                    }
                    hlodCull.m_BackSort = backList;
                    EditorUtility.ClearProgressBar();
                    EditorUtility.SetDirty(m_RootVolume);
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();
                    EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());
                    //AutoLOD.sceneLODEnabled = false;

                    if (s_endCall != null)
                    {
                        s_endCall.Invoke(m_RootVolume.gameObject, hlods.gameObject);
                    }
                }));
            }
            else
            {
                EditorUtility.ClearProgressBar();
                if (s_endCall != null)
                {
                    s_endCall.Invoke(null, null);
                }
            }
#endif
            while (m_CoroutineQueue.Count > 0)
            {
                yield return(MonoBehaviourHelper.StartCoroutine(m_CoroutineQueue.Dequeue()));
            }
        }
示例#11
0
 public void ClearProgressBar()
 {
     EditorUtility.ClearProgressBar();
 }
示例#12
0
        /// <summary>
        /// Migrates all objects from list of objects to be migrated using the selected IMigrationHandler implementation.
        /// </summary>
        /// <param name="type">A type that implements IMigrationhandler</param>
        public bool MigrateSelection(Type type, bool askForConfirmation)
        {
            if (migrationObjects.Count == 0)
            {
                Debug.LogError($"List of objects for migration is empty.");
                return(false);
            }

            if (migrationHandlerInstanceType == null)
            {
                Debug.LogError($"Please select type for migration.");
                return(false);
            }

            if (type == null || migrationHandlerInstanceType != type)
            {
                Debug.LogError($"Selected objects should be migrated with type: {migrationHandlerInstanceType}");
                return(false);
            }

            if (askForConfirmation && !EditorUtility.DisplayDialog("Migration Window",
                                                                   "Migration operation cannot be reverted.\n\nDo you want to continue?", "Continue", "Cancel"))
            {
                return(false);
            }

            if (askForConfirmation && !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                return(false);
            }
            var previousScenePath = EditorSceneManager.GetActiveScene().path;
            int failures          = 0;

            MigrationState = MigrationToolState.Migrating;

            for (int i = 0; i < migrationObjects.Count; i++)
            {
                var progress = (float)i / migrationObjects.Count;
                if (EditorUtility.DisplayCancelableProgressBar("Migration Tool", $"Migrating all {type.Name} components from selection", progress))
                {
                    break;
                }
                string assetPath = AssetDatabase.GetAssetPath(migrationObjects.ElementAt(i).Key);

                if (IsSceneGameObject(migrationObjects.ElementAt(i).Key))
                {
                    MigrateGameObjectHierarchy((GameObject)migrationObjects.ElementAt(i).Key, migrationObjects.ElementAt(i).Value);
                }
                else if (IsPrefabAsset(migrationObjects.ElementAt(i).Key))
                {
                    PrefabAssetType prefabType = PrefabUtility.GetPrefabAssetType(migrationObjects.ElementAt(i).Key);
                    if (prefabType == PrefabAssetType.Regular || prefabType == PrefabAssetType.Variant)
                    {
                        // there's currently 5 types of prefab asset types - we're supporting the following:
                        // - Regular: a regular prefab object
                        // - Variant: a prefab derived from another prefab which could be a model, regular or variant prefab
                        // we won't support the following types:
                        // - Model: we can't migrate fbx or other mesh files
                        // - MissingAsset: we can't migrate missing data
                        // - NotAPrefab: we can't migrate as prefab if the given asset isn't a prefab
                        MigratePrefab(assetPath, migrationObjects.ElementAt(i).Value);
                    }
                }
                else if (IsSceneAsset(migrationObjects.ElementAt(i).Key))
                {
                    MigrateScene(assetPath, migrationObjects.ElementAt(i).Value);
                }
                migrationObjects.ElementAt(i).Value.IsProcessed = true;
                failures += migrationObjects.ElementAt(i).Value.Failures;

                Debug.Log(migrationObjects.ElementAt(i).Value.Log);
            }
            EditorUtility.ClearProgressBar();

            if (!String.IsNullOrEmpty(previousScenePath) && previousScenePath != EditorSceneManager.GetActiveScene().path)
            {
                EditorSceneManager.OpenScene(Path.Combine(Directory.GetCurrentDirectory(), previousScenePath));
            }

            if (askForConfirmation)
            {
                string msg;
                if (failures > 0)
                {
                    msg = $"Migration completed with {failures} errors";
                }
                else
                {
                    msg = "Migration completed successfully!";
                }
                EditorUtility.DisplayDialog("Migration Window", msg, "Close");
            }

            MigrationState = MigrationToolState.PostMigration;
            return(true);
        }
 private static void OnEditorInitialize()
 {
     EditorUtility.ClearProgressBar();
     BuildScript.GetManifest();
     BuildScript.GetBuildRules();
 }
示例#14
0
    private List <GameObject> getFilteredItems()
    {
        if (allPrefabsInProject == null)
        {
            allPrefabsInProject = new List <GameObject>();

            var progressTime = Environment.TickCount;

            var allAssetPaths = AssetDatabase.GetAllAssetPaths();
            for (int i = 0; i < allAssetPaths.Length; i++)
            {
                if (Environment.TickCount - progressTime > 250)
                {
                    progressTime = Environment.TickCount;
                    EditorUtility.DisplayProgressBar(this.title, "Loading prefabs", (float)i / (float)allAssetPaths.Length);
                }

                var path = allAssetPaths[i];
                if (!path.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                try
                {
                    var gameObject = AssetDatabase.LoadMainAssetAtPath(path) as GameObject;
                    if (IsPrefab(gameObject))
                    {
                        allPrefabsInProject.Add(gameObject);
                    }
                }
                catch (Exception err)
                {
                    Debug.LogError("Error loading prefab at " + path + " - " + err.Message);
                }
            }

            EditorUtility.ClearProgressBar();

            allPrefabsInProject.Sort((GameObject lhs, GameObject rhs) =>
            {
                return(lhs.name.CompareTo(rhs.name));
            });
        }

        var result = new List <GameObject>();

        foreach (var item in allPrefabsInProject)
        {
            if (item == null || item.GetComponent(componentType) == null)
            {
                continue;
            }

            try
            {
                if (filterCallback != null && !filterCallback(item))
                {
                    continue;
                }
            }
            catch { continue; }

            if (item.name.IndexOf(searchFilter, StringComparison.OrdinalIgnoreCase) != -1)
            {
                result.Add(item);
            }
        }

        return(result);
    }
        static void ProcessUpdateMaterial(string caption, float scriptVersion, UpdateMaterial updateMaterial, UpdateMaterialFile updateMaterialFile = null)
        {
            bool          VCSEnabled    = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
            var           matIds        = AssetDatabase.FindAssets("t:Material");
            List <string> materialFiles = new List <string>(); // Contain the list dirty files

            try
            {
                for (int i = 0, length = matIds.Length; i < length; i++)
                {
                    var path = AssetDatabase.GUIDToAssetPath(matIds[i]);
                    var mat  = AssetDatabase.LoadAssetAtPath <Material>(path);

                    EditorUtility.DisplayProgressBar(
                        "Update material " + caption + "...",
                        string.Format("{0} / {1} materials updated.", i, length),
                        i / (float)(length - 1));

                    bool isHDRPShader = mat.shader.name == "HDRP/LitTessellation" ||
                                        mat.shader.name == "HDRP/Lit" ||
                                        mat.shader.name == "HDRP/LayeredLit" ||
                                        mat.shader.name == "HDRP/LayeredLitTessellation" ||
                                        mat.shader.name == "HDRP/StackLit" ||
                                        mat.shader.name == "HDRP/Unlit" ||
                                        mat.shader.name == "HDRP/Fabric" ||
                                        mat.shader.name == "HDRP/Decal" ||
                                        mat.shader.name == "HDRP/TerrainLit";

                    if (mat.shader.IsShaderGraph())
                    {
                        var outputNodeType = GraphUtil.GetOutputNodeType(AssetDatabase.GetAssetPath(mat.shader));

                        isHDRPShader |= outputNodeType == typeof(HDUnlitMasterNode);
                        isHDRPShader |= outputNodeType == typeof(HDLitMasterNode);
                        isHDRPShader |= outputNodeType == typeof(HairMasterNode);
                        isHDRPShader |= outputNodeType == typeof(FabricMasterNode);
                        isHDRPShader |= outputNodeType == typeof(StackLitMasterNode);
                    }

                    if (isHDRPShader)
                    {
                        // We don't handle embed material as we can't rewrite fbx files
                        if (Path.GetExtension(path).ToLower() == ".fbx")
                        {
                            continue;
                        }

                        bool dirty = updateMaterial(path, mat);

                        // Checkout the file and tag it as dirty
                        if (dirty)
                        {
                            CoreEditorUtils.CheckOutFile(VCSEnabled, mat);
                            EditorUtility.SetDirty(mat);
                            materialFiles.Add(path);
                        }
                    }
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                // Save all dirty assets
                AssetDatabase.SaveAssets();
            }

            if (updateMaterialFile == null)
            {
                return;
            }

            // Now that all the asset have been modified and save, we can safely update the .mat file and remove removed property
            try
            {
                for (int i = 0, length = materialFiles.Count; i < length; i++)
                {
                    string path = materialFiles[i];

                    EditorUtility.DisplayProgressBar(
                        "Update .mat files...",
                        string.Format("{0} / {1} materials .mat file updated.", i, length),
                        i / (float)(length - 1));

                    // Note: The file is supposed to be checkout by the previous loop
                    updateMaterialFile(path);
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                // No need to save in this case
            }
        }
示例#16
0
        /// <summary>
        /// 拷贝本地AssetBunle至StreamingAssets目录
        /// </summary>
        public static bool CopyNativeAssetBundleToStreamingAssets(ResourcesManifest resources_manifest)
        {
            if (resources_manifest == null)
            {
                return(false);
            }

            //清空本地资源目录
            if (ShowProgressBar("", "清空本地资源目录", 0f))
            {
                EditorUtility.ClearProgressBar();
                return(false);
            }
            if (!Directory.Exists(Common.INITIAL_PATH))
            {
                Directory.CreateDirectory(Common.INITIAL_PATH);
            }
            else
            {
                zcode.FileHelper.DeleteAllChild(Common.INITIAL_PATH
                                                , FileAttributes.Hidden | FileAttributes.System);
            }

            //拷贝所有配置文件
            for (int i = 0; i < Common.MAIN_CONFIG_NAME_ARRAY.Length; ++i)
            {
                string file           = Common.MAIN_CONFIG_NAME_ARRAY[i];
                string src_file_name  = EditorCommon.BUILD_PATH + "/" + file;
                string dest_file_name = Common.INITIAL_PATH + "/" + file;
                float  progress       = (float)(i + 1) / (float)Common.MAIN_CONFIG_NAME_ARRAY.Length;
                if (ShowProgressBar("", "Copy " + file, progress))
                {
                    EditorUtility.ClearProgressBar();
                    return(false);
                }
                zcode.FileHelper.CopyFile(src_file_name, dest_file_name, true);
            }

            //拷贝AssetBundle文件
            if (resources_manifest.Data != null && resources_manifest.Data.AssetBundles != null)
            {
                float current = 0f;
                float total   = resources_manifest.Data.AssetBundles.Count;
                foreach (var desc in resources_manifest.Data.AssetBundles.Values)
                {
                    current += 1f;

                    //过滤主AssetBundle文件
                    if (desc.AssetBundleName == Common.MAIN_MANIFEST_FILE_NAME)
                    {
                        continue;
                    }

                    if (desc.IsNative)
                    {
                        zcode.FileHelper.CopyFile(EditorCommon.BUILD_PATH + "/" + desc.AssetBundleName
                                                  , Common.INITIAL_PATH + "/" + desc.AssetBundleName, true);
                    }

                    //更新进度条
                    if (ShowProgressBar("", "Copy " + desc.AssetBundleName, current / total))
                    {
                        EditorUtility.ClearProgressBar();
                        return(false);
                    }
                }
            }

            EditorUtility.ClearProgressBar();
            AssetDatabase.Refresh();

            return(true);
        }
示例#17
0
    /// <summary>
    /// Combine all sprites into a single texture and save it to disk.
    /// </summary>

    static public bool UpdateTexture(INGUIAtlas atlas, List <SpriteEntry> sprites)
    {
        // Get the texture for the atlas
        var tex     = atlasTexture;
        var oldPath = (tex != null) ? AssetDatabase.GetAssetPath(tex.GetInstanceID()) : "";
        var newPath = NGUIEditorTools.GetSaveableTexturePath(atlas as Object, atlasTexture);

        // Clear the read-only flag in texture file attributes
        if (System.IO.File.Exists(newPath))
        {
            System.IO.FileAttributes newPathAttrs = System.IO.File.GetAttributes(newPath);
            newPathAttrs &= ~System.IO.FileAttributes.ReadOnly;
            System.IO.File.SetAttributes(newPath, newPathAttrs);
        }

        bool newTexture = (tex == null || oldPath != newPath);

        if (newTexture)
        {
            // Create a new texture for the atlas
            tex = new Texture2D(1, 1, TextureFormat.ARGB32, false);
        }
        else
        {
            // Make the atlas readable so we can save it
            tex = NGUIEditorTools.ImportTexture(oldPath, true, false, false);
        }

        // Pack the sprites into this texture
        if (PackTextures(tex, sprites))
        {
            var bytes = tex.EncodeToPNG();
            System.IO.File.WriteAllBytes(newPath, bytes);
            bytes = null;

            // Load the texture we just saved as a Texture2D
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
            tex = NGUIEditorTools.ImportTexture(newPath, false, true, !premultipliedAlpha);

            // Update the atlas texture
            if (newTexture)
            {
                if (tex == null)
                {
                    Debug.LogError("Failed to load the created atlas saved as " + newPath);
                    EditorUtility.ClearProgressBar();
                }
                else
                {
                    var mat = spriteMaterial;

                    if (mat == null)
                    {
                        var matPath = newPath.Replace(".png", ".mat");
                        var shader  = Shader.Find(NGUISettings.atlasPMA ? "Unlit/Premultiplied Colored" : "Unlit/Transparent Colored");
                        mat = new Material(shader);

                        // Save the material
                        AssetDatabase.CreateAsset(mat, matPath);
                        AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

                        // Load the material so it's usable
                        mat            = AssetDatabase.LoadAssetAtPath <Material>(matPath);
                        spriteMaterial = mat;
                    }

                    mat.mainTexture = tex;
                }

                ReleaseSprites(sprites);

                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
            }
            return(true);
        }
        else
        {
            if (!newTexture)
            {
                NGUIEditorTools.ImportTexture(oldPath, false, true, !premultipliedAlpha);
            }

            //Debug.LogError("Operation canceled: The selected sprites can't fit into the atlas.\n" +
            //	"Keep large sprites outside the atlas (use UITexture), and/or use multiple atlases instead.");

            EditorUtility.DisplayDialog("Operation Canceled", "The selected sprites can't fit into the atlas.\n" +
                                        "Keep large sprites outside the atlas (use UITexture), and/or use multiple atlases instead", "OK");
            return(false);
        }
    }
示例#18
0
        /// <summary>
        /// 压缩AssetBundle
        /// </summary>
        public static bool CompressAssetBundles(ResourcesManifest old_resources_manifest, ref ResourcesManifest resources_manifest)
        {
            if (resources_manifest == null)
            {
                return(false);
            }
            if (resources_manifest.Data == null)
            {
                return(false);
            }
            if (resources_manifest.Data.AssetBundles == null)
            {
                return(false);
            }

            // 通过记录新旧版本中压缩标记
            // 判定资源是否需要压缩、删除压缩包
            Dictionary <string, int> dic = new Dictionary <string, int>();
            int old_version_bit          = 0x1;             // 旧版本中压缩
            int new_version_bit          = 0x2;             // 新版本中压缩

            if (old_resources_manifest.Data != null && old_resources_manifest.Data.AssetBundles != null)
            {
                var itr = old_resources_manifest.Data.AssetBundles.GetEnumerator();
                while (itr.MoveNext())
                {
                    if (itr.Current.Value.IsCompress)
                    {
                        string name = itr.Current.Value.AssetBundleName;
                        if (!dic.ContainsKey(name))
                        {
                            dic.Add(name, old_version_bit);
                        }
                        else
                        {
                            dic[name] |= old_version_bit;
                        }
                    }
                }
            }
            {
                var itr = resources_manifest.Data.AssetBundles.GetEnumerator();
                while (itr.MoveNext())
                {
                    if (itr.Current.Value.IsCompress)
                    {
                        string name = itr.Current.Value.AssetBundleName;
                        if (!dic.ContainsKey(name))
                        {
                            dic.Add(name, new_version_bit);
                        }
                        else
                        {
                            dic[name] |= new_version_bit;
                        }
                    }
                }
            }

            float current = 0f;
            float total   = resources_manifest.Data.AssetBundles.Count;
            var   itr1    = dic.GetEnumerator();

            while (itr1.MoveNext())
            {
                string name = itr1.Current.Key;
                int    mask = itr1.Current.Value;

                //过滤主AssetBundle文件
                if (name == Common.MAIN_MANIFEST_FILE_NAME)
                {
                    continue;
                }

                string action;
                string file_name = EditorCommon.BUILD_PATH + "/" + name;
                if ((mask & old_version_bit) > 0 &&
                    (mask & new_version_bit) == 0)
                {
                    // 旧版本中存在,新版本不存在
                    // 删除压缩包
                    string compress_file = Compress.GetCompressFileName(file_name);
                    File.Delete(compress_file);
                    File.Delete(compress_file + Common.NATIVE_MANIFEST_EXTENSION);

                    //重写ResourcesManifest数据
                    var ab = resources_manifest.Data.AssetBundles[name];
                    ab.CompressSize = 0;

                    action = "Delete Compress";
                }
                else if ((mask & new_version_bit) > 0)
                {
                    //新版本中存在,压缩文件
                    Compress.CompressFile(file_name);

                    //重写ResourcesManifest数据
                    var ab = resources_manifest.Data.AssetBundles[name];
                    ab.CompressSize = zcode.FileHelper.GetFileSize(Compress.GetCompressFileName(file_name));

                    action = "Compress";
                }
                else
                {
                    action = "Ignore";
                }

                //更新进度条
                if (ShowProgressBar("", action + " " + name, current / total))
                {
                    EditorUtility.ClearProgressBar();
                    return(false);
                }
            }

            EditorUtility.ClearProgressBar();
            return(true);
        }
示例#19
0
    static void CreateIndex()
    {
        tk2dIndex newIndex = ScriptableObject.CreateInstance <tk2dIndex>();

        newIndex.version   = tk2dIndex.CURRENT_VERSION;
        newIndex.hideFlags = HideFlags.DontSave;         // get this to not be destroyed in Unity 4.1

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

        // check all prefabs to see if we can find any objects we are interested in
        List <string>  allPrefabPaths = new List <string>();
        Stack <string> paths          = new Stack <string>();

        paths.Push(Application.dataPath);
        while (paths.Count != 0)
        {
            string   path  = paths.Pop();
            string[] files = Directory.GetFiles(path, "*.prefab");
            foreach (var file in files)
            {
                allPrefabPaths.Add(file.Substring(Application.dataPath.Length - 6));
            }

            foreach (string subdirs in Directory.GetDirectories(path))
            {
                paths.Push(subdirs);
            }
        }

        // Check all prefabs
        int currPrefabCount = 1;

        foreach (string prefabPath in allPrefabPaths)
        {
            EditorUtility.DisplayProgressBar("Rebuilding Index", "Scanning project folder...", (float)currPrefabCount / (float)(allPrefabPaths.Count));

            GameObject iterGo = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
            if (!iterGo)
            {
                continue;
            }

            tk2dSpriteCollection     spriteCollection     = iterGo.GetComponent <tk2dSpriteCollection>();
            tk2dSpriteCollectionData spriteCollectionData = iterGo.GetComponent <tk2dSpriteCollectionData>();
            tk2dFont            font = iterGo.GetComponent <tk2dFont>();
            tk2dSpriteAnimation anim = iterGo.GetComponent <tk2dSpriteAnimation>();

            if (spriteCollection)
            {
                tk2dSpriteCollectionData thisSpriteCollectionData = spriteCollection.spriteCollection;
                if (thisSpriteCollectionData)
                {
                    if (thisSpriteCollectionData.version < 1)
                    {
                        rebuildSpriteCollectionPaths.Add(AssetDatabase.GetAssetPath(spriteCollection));
                    }
                    newIndex.AddSpriteCollectionData(thisSpriteCollectionData);
                }
            }
            else if (spriteCollectionData)
            {
                string guid    = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(spriteCollectionData));
                bool   present = false;
                foreach (var v in newIndex.GetSpriteCollectionIndex())
                {
                    if (v.spriteCollectionDataGUID == guid)
                    {
                        present = true;
                        break;
                    }
                }
                if (!present && guid != "")
                {
                    newIndex.AddSpriteCollectionData(spriteCollectionData);
                }
            }
            else if (font)
            {
                newIndex.AddOrUpdateFont(font);                 // unfortunate but necessary
            }
            else if (anim)
            {
                newIndex.AddSpriteAnimation(anim);
            }
            else
            {
                iterGo = null;
                System.GC.Collect();
            }

            tk2dEditorUtility.UnloadUnusedAssets();
            ++currPrefabCount;
        }
        EditorUtility.ClearProgressBar();

        // Create index
        newIndex.hideFlags = 0;         // to save it
        AssetDatabase.CreateAsset(newIndex, indexPath);
        AssetDatabase.SaveAssets();

        // unload all unused assets
        tk2dEditorUtility.UnloadUnusedAssets();

        // Rebuild invalid sprite collections
        if (rebuildSpriteCollectionPaths.Count > 0)
        {
            EditorUtility.DisplayDialog("Upgrade required",
                                        "Please wait while your sprite collection is upgraded.",
                                        "Ok");

            int count = 1;
            foreach (var scPath in rebuildSpriteCollectionPaths)
            {
                tk2dSpriteCollection sc = AssetDatabase.LoadAssetAtPath(scPath, typeof(tk2dSpriteCollection)) as tk2dSpriteCollection;
                EditorUtility.DisplayProgressBar("Rebuilding Sprite Collections", "Rebuilding Sprite Collection: " + sc.name, (float)count / (float)(rebuildSpriteCollectionPaths.Count));

                tk2dSpriteCollectionBuilder.Rebuild(sc);
                sc = null;

                tk2dEditorUtility.UnloadUnusedAssets();

                ++count;
            }

            EditorUtility.ClearProgressBar();
        }

        index = newIndex;
        tk2dSpriteGuiUtility.ResetCache();
    }
 void OnDestroy()
 {
     EditorUtility.ClearProgressBar();
     Resources.UnloadUnusedAssets();
 }
示例#21
0
    Mesh[] CreateMesh()
    {
        NavMeshTriangulation triangulatedNavMesh = NavMesh.CalculateTriangulation();

        Vector3[]      navVertices = triangulatedNavMesh.vertices;
        List <Vector3> vertices    = new List <Vector3>();

        vertices.AddRange(navVertices);
        vertices.Sort(delegate(Vector3 v1, Vector3 v2) { return(v1.x == v2.x ? (v1.z == v2.z ? 0 : (v1.z < v2.z ? -1 : 1)) : (v1.x < v2.x ? -1 : 1)); });

        Vector3[] v = vertices.ToArray();

        int[] table = new int[triangulatedNavMesh.vertices.Length];

        for (int i = 0; i < table.Length; i++)
        {
            table[i] = Find(v, 0, vertices.Count, navVertices[i], navVertices[i].x - 0.001f);
            if ((i % 100) == 0)
            {
                EditorUtility.DisplayProgressBar(string.Format("Export Nav-Mesh (Phase #1/3) {0}/{1}", i, table.Length), "Weld Vertex", Mathf.InverseLerp(0, table.Length, i));
            }
        }

        int[] navTriangles = triangulatedNavMesh.indices;

        List <Tri> tri = new List <Tri> ();

        for (int i = 0; i < navTriangles.Length; i += 3)
        {
            tri.Add(new Tri(table[navTriangles[i + 0]], table[navTriangles[i + 1]], table[navTriangles[i + 2]]));
        }
        tri.Sort(delegate(Tri t1, Tri t2) { return(t1.min == t2.min ? 0 : t1.min < t2.min ? -1 : 1); });

        int[] boundmin = new int[(tri.Count + 127) / 128];
        int[] boundmax = new int[boundmin.Length];

        for (int i = 0, c = 0; i < tri.Count; i += 128, c++)
        {
            int min = tri[i].min;
            int max = tri[i].max;
            for (int j = 1; j < 128 && i + j < tri.Count; j++)
            {
                min = Mathf.Min(tri[i + j].min, min);
                max = Mathf.Max(tri[i + j].max, max);
            }
            boundmin[c] = min;
            boundmax[c] = max;
        }

        int[] triangles = new int[navTriangles.Length];
        for (int i = 0; i < triangles.Length; i += 3)
        {
            triangles[i + 0] = tri[i / 3].i1;
            triangles[i + 1] = tri[i / 3].i2;
            triangles[i + 2] = tri[i / 3].i3;
        }

        List <int> groupidx   = new List <int>();
        List <int> groupcount = new List <int>();

        int[] group = new int[triangles.Length / 3];

        for (int i = 0; i < triangles.Length; i += 3)
        {
            int groupid = -1;
            int max     = Mathf.Max(triangles[i], triangles[i + 1], triangles[i + 2]);
            int min     = Mathf.Min(triangles[i], triangles[i + 1], triangles[i + 2]);

            for (int b = 0, c = 0; b < i; b += 3 * 128, c++)
            {
                if (boundmin[c] > max || boundmax[c] < min)
                {
                    continue;
                }

                for (int j = b; j < i && j < b + 3 * 128; j += 3)
                {
                    if (tri[j / 3].min > max)
                    {
                        break;
                    }

                    if (tri[j / 3].max < min)
                    {
                        continue;
                    }

                    if (groupidx[group[j / 3]] == groupid)
                    {
                        continue;
                    }

                    for (int k = 0; k < 3; k++)
                    {
                        int vi = triangles[j + k];
                        if (triangles[i] == vi || triangles[i + 1] == vi || triangles[i + 2] == vi)
                        {
                            if (groupid == -1)
                            {
                                groupid      = groupidx[group[j / 3]];
                                group[i / 3] = groupid;
                            }
                            else
                            {
                                int curgroup = groupidx[group[j / 3]];
                                for (int l = 0; l < groupidx.Count; l++)
                                {
                                    if (groupidx[l] == curgroup)
                                    {
                                        groupidx[l] = groupid;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }

            if (groupid == -1)
            {
                groupid      = groupidx.Count;
                group[i / 3] = groupid;
                groupidx.Add(groupid);
                groupcount.Add(0);
            }

            if (((i / 3) % 100) == 0)
            {
                EditorUtility.DisplayProgressBar("Collect (Phase #2/3)", "Classification Group", Mathf.InverseLerp(0, triangles.Length, i));
            }
        }

        for (int i = 0; i < triangles.Length; i += 3)
        {
            group[i / 3] = groupidx[group[i / 3]];
            groupcount[group[i / 3]]++;
        }

        List <Mesh> result = new List <Mesh>();

        List <Vector3> vtx     = new List <Vector3>();
        List <int>     indices = new List <int>();

        int[] newtable = new int[vertices.Count];
        for (int i = 0; i < newtable.Length; i++)
        {
            newtable[i] = -1;
        }

        Vector3[] walkpoint = m_WalkablePoint.ToArray();

        for (int g = 0; g < groupcount.Count; g++)
        {
            if (groupcount[g] == 0)
            {
                continue;
            }

            List <Vector3> isolatevtx = new List <Vector3>();
            List <int>     iolateidx  = new List <int>();

            for (int i = 0; i < triangles.Length; i += 3)
            {
                if (group[i / 3] == g)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        int idx = triangles[i + j];
                        if (newtable[idx] == -1)
                        {
                            newtable[idx] = isolatevtx.Count;
                            isolatevtx.Add(transform.InverseTransformPoint(vertices[idx] + Vector3.up * m_Offset));
                        }
                    }
                    iolateidx.Add(newtable[triangles[i + 0]]);
                    iolateidx.Add(newtable[triangles[i + 1]]);
                    iolateidx.Add(newtable[triangles[i + 2]]);
                }
            }

            if (Contains(isolatevtx.ToArray(), iolateidx.ToArray(), walkpoint) == true)
            {
                continue;
            }

            int maxvertex = 32768;

            if (vtx.Count > maxvertex || vtx.Count + isolatevtx.Count * (2 + m_MidLayerCount) >= 65536)
            {
                result.Add(CreateMesh(vtx.ToArray(), indices.ToArray()));
                vtx.Clear();
                indices.Clear();
            }

            Vector3 h         = transform.InverseTransformVector(Vector3.up * m_Height);
            int     vtxoffset = vtx.Count;
            int     layer     = 2 + m_MidLayerCount;
            for (int i = 0; i < isolatevtx.Count; i++)
            {
                for (int j = 0; j < layer; j++)
                {
                    vtx.Add(isolatevtx[i] + h * ((float)j / (layer - 1)));
                }
            }
            for (int i = 0; i < iolateidx.Count; i += 3)
            {
                for (int j = 0; j < layer; j++)
                {
                    if (j == 0)
                    {
                        indices.AddRange(new int[] { vtxoffset + iolateidx[i] * layer + j, vtxoffset + iolateidx[i + 2] * layer + j, vtxoffset + iolateidx[i + 1] * layer + j });
                    }
                    else
                    {
                        indices.AddRange(new int[] { vtxoffset + iolateidx[i] * layer + j, vtxoffset + iolateidx[i + 1] * layer + j, vtxoffset + iolateidx[i + 2] * layer + j });
                    }
                }
            }

            if (m_Height > 0)
            {
                List <Edge> edge = new List <Edge>();
                for (int i = 0; i < iolateidx.Count; i += 3)
                {
                    edge.Add(new Edge(iolateidx[i + 0], iolateidx[i + 1]));
                    edge.Add(new Edge(iolateidx[i + 1], iolateidx[i + 2]));
                    edge.Add(new Edge(iolateidx[i + 2], iolateidx[i + 0]));
                }
                edge.Sort(delegate(Edge e1, Edge e2) { return(e1.i1 == e2.i1 ? 0 : (e1.i1 < e2.i1 ? -1 : 1)); });
                Edge[] e = edge.ToArray();

                for (int i = 0; i < iolateidx.Count; i += 3)
                {
                    for (int i1 = 2, i2 = 0; i2 < 3; i1 = i2++)
                    {
                        int v1 = iolateidx[i + i1];
                        int v2 = iolateidx[i + i2];

                        if (!Find(e, 0, edge.Count, v2, v1))
                        {
                            if (vtx.Count + 4 >= 65536)
                            {
                                result.Add(CreateMesh(vtx.ToArray(), indices.ToArray()));
                                vtx.Clear();
                                indices.Clear();
                            }

                            indices.AddRange(new int[] { vtx.Count, vtx.Count + 1, vtx.Count + 3, vtx.Count, vtx.Count + 3, vtx.Count + 2 });
                            vtx.AddRange(new Vector3[] { isolatevtx[v1], isolatevtx[v2], isolatevtx[v1] + h, isolatevtx[v2] + h });
                        }
                    }

                    if ((i % 600) == 0)
                    {
                        EditorUtility.DisplayProgressBar("Collect (Phase #3/3)", "Create Mesh", Mathf.InverseLerp(0, groupcount.Count * 100, g * 100 + i * 100 / (i - iolateidx.Count)));
                    }
                }
            }

            EditorUtility.DisplayProgressBar("Collect (Phase #3/3)", "Create Mesh", Mathf.InverseLerp(0, groupcount.Count, g));
        }

        if (vtx.Count > 0)
        {
            result.Add(CreateMesh(vtx.ToArray(), indices.ToArray()));
        }

        EditorUtility.ClearProgressBar();
        return(result.ToArray());
    }
示例#22
0
        public List <FindResult> FuncReturn(Func <FindResult, bool> input)
        {
            references.Clear();
            string appDataPath = Application.dataPath;
            int    cpuCount    = Environment.ProcessorCount;
            var    keyword     = isFileID ? string.Format("\"fileID: {0}, guid: {1}\"", targetFileID, targetGUID) : string.Format("\"guid: {0}\"", targetGUID);
            var    psi         = new ProcessStartInfo();

            if (Application.platform == RuntimePlatform.OSXEditor)
            {
                psi.FileName          = "/usr/bin/mdfind";
                psi.Arguments         = string.Format("-onlyin {0} {1}", appDataPath, keyword);
                totalWaitMilliseconds = 2 * 1000;
            }
            else
            {
                psi.FileName  = Path.Combine(Environment.CurrentDirectory, @"Tool\rg.exe");
                psi.Arguments = string.Format("--case-sensitive --follow --files-with-matches --no-text --fixed-strings " +
                                              "--ignore-file Assets/Editor/ignore.txt " +
                                              "--threads {0} --regexp {1} -- {2}",
                                              cpuCount, keyword, appDataPath);
            }

            psi.UseShellExecute        = false;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError  = true;
            psi.CreateNoWindow         = true;

            Process process = new Process();

            process.StartInfo = psi;

            process.OutputDataReceived += (sender, e) =>
            {
                if (string.IsNullOrEmpty(e.Data))
                {
                    return;
                }

                string relativePath = e.Data.Replace(appDataPath, "Assets").Replace("\\", "/");
                references.Add(relativePath);
            };

            process.ErrorDataReceived += (sender, e) =>
            {
                if (string.IsNullOrEmpty(e.Data))
                {
                    return;
                }
            };

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            while (!process.HasExited)
            {
                if (stopwatch.ElapsedMilliseconds < totalWaitMilliseconds)
                {
                    float  progress = (float)((double)stopwatch.ElapsedMilliseconds / totalWaitMilliseconds);
                    string info     = string.Format("Finding {0}/{1}s {2:P2}", stopwatch.ElapsedMilliseconds / 1000,
                                                    totalWaitMilliseconds / 1000, progress);
                    bool canceled = EditorUtility.DisplayCancelableProgressBar("Find References in Project", info, progress);

                    if (canceled)
                    {
                        process.Kill();
                        break;
                    }

                    Thread.Sleep(100);
                }
                else
                {
                    process.Kill();
                    break;
                }
            }
            var list = new List <FindResult>();

            for (int i = 0, len = references.Count; i < len; ++i)
            {
                var    file      = references[i];
                string assetPath = file;
                if (file.EndsWith(".meta"))
                {
                    assetPath = file.Substring(0, file.Length - ".meta".Length);
                }

                var obj = AssetDatabase.LoadMainAssetAtPath(assetPath) as GameObject;
                if (obj != null)
                {
                    var find = new FindResult
                    {
                        go   = obj,
                        name = obj.name,
                        path = assetPath,
                    };
                    if (input == null || input(find))
                    {
                        list.Add(find);
                    }
                }
            }

            EditorUtility.ClearProgressBar();
            stopwatch.Stop();
            return(list);
        }
示例#23
0
 private void OnLoadCompleted()
 {
     EditorUtility.ClearProgressBar();
 }
        /// <summary>
        /// 准备工作
        /// </summary>
        private List <AssetInfo> GetBuildMap()
        {
            int progressBarCount = 0;
            Dictionary <string, AssetInfo> buildMap = new Dictionary <string, AssetInfo>();

            // 获取要收集的资源
            List <string> allCollectAssets = AssetBundleCollectorSettingData.GetAllCollectAssets();

            // 进行依赖分析
            foreach (string mainAssetPath in allCollectAssets)
            {
                List <AssetInfo> depends = GetDependencies(mainAssetPath);
                for (int i = 0; i < depends.Count; i++)
                {
                    AssetInfo assetInfo = depends[i];
                    if (buildMap.ContainsKey(assetInfo.AssetPath))
                    {
                        buildMap[assetInfo.AssetPath].DependCount++;
                    }
                    else
                    {
                        buildMap.Add(assetInfo.AssetPath, assetInfo);
                    }
                }
                progressBarCount++;
                EditorUtility.DisplayProgressBar("进度", $"依赖文件分析:{progressBarCount}/{allCollectAssets.Count}", (float)progressBarCount / allCollectAssets.Count);
            }
            EditorUtility.ClearProgressBar();
            progressBarCount = 0;

            // 移除零依赖的资源
            List <string> removeList = new List <string>();

            foreach (KeyValuePair <string, AssetInfo> pair in buildMap)
            {
                if (pair.Value.IsCollectAsset)
                {
                    continue;
                }
                if (pair.Value.DependCount == 0)
                {
                    removeList.Add(pair.Value.AssetPath);
                }
            }
            for (int i = 0; i < removeList.Count; i++)
            {
                buildMap.Remove(removeList[i]);
            }

            // 设置资源标签
            foreach (KeyValuePair <string, AssetInfo> pair in buildMap)
            {
                var assetInfo       = pair.Value;
                var labelAndVariant = AssetBundleCollectorSettingData.GetBundleLabelAndVariant(assetInfo.AssetPath);
                assetInfo.AssetBundleLabel   = labelAndVariant.BundleLabel;
                assetInfo.AssetBundleVariant = labelAndVariant.BundleVariant;
                progressBarCount++;
                EditorUtility.DisplayProgressBar("进度", $"设置资源标签:{progressBarCount}/{buildMap.Count}", (float)progressBarCount / buildMap.Count);
            }
            EditorUtility.ClearProgressBar();

            // 返回结果
            return(buildMap.Values.ToList());
        }
示例#25
0
 private void OnProcessAssetBundleComplete(Platform platform, string versionListPath, int versionListLength, int versionListHashCode, int versionListZipLength, int versionListZipHashCode)
 {
     EditorUtility.ClearProgressBar();
     Debug.Log(Utility.Text.Format("Build AssetBundles for '{0}' complete, version list path is '{1}', length is '{2}', hash code is '{3}', zip length is '{4}', zip hash code is '{5}'.", platform.ToString(), versionListPath, versionListLength.ToString(), versionListHashCode.ToString("X8"), versionListZipLength.ToString(), versionListZipHashCode.ToString("X8")));
 }
示例#26
0
        private static void Delay()
        {
            if (InkLibrary.FilesInCompilingStackInState(CompilationStackItem.State.Compiling).Count > 0)
            {
                Debug.LogWarning("Delayed, but a file is now compiling! You can ignore this warning.");
                return;
            }
            bool   errorsFound = false;
            string listOfFiles = "\nFiles compiled:";

            foreach (var compilingFile in InkLibrary.Instance.compilationStack)
            {
                listOfFiles += "\n";
                listOfFiles += compilingFile.inkFile.filePath;
                if (compilingFile.errorOutput != "")
                {
                    listOfFiles += " (With unhandled error)";
                    Debug.LogError("Unhandled error occurred compiling Ink file " + compilingFile.inkFile + "! Please report following error as a bug:\n" + compilingFile.errorOutput);
                    compilingFile.inkFile.compileErrors.Clear();
                    compilingFile.inkFile.compileErrors.Add(compilingFile.errorOutput);
                    errorsFound = true;
                }
                else
                {
                    SetOutputLog(compilingFile);
                    bool errorsInEntireStory   = false;
                    bool warningsInEntireStory = false;
                    foreach (var inkFile in compilingFile.inkFile.inkFilesInIncludeHierarchy)
                    {
                        if (inkFile.hasErrors)
                        {
                            errorsInEntireStory = true;
                        }
                        if (inkFile.hasWarnings)
                        {
                            warningsInEntireStory = true;
                        }
                    }
                    if (errorsInEntireStory)
                    {
                        listOfFiles += " (With error)";
                        errorsFound  = true;
                    }
                    else
                    {
                        string localJSONAssetPath = InkEditorUtils.AbsoluteToUnityRelativePath(compilingFile.jsonAbsoluteFilePath);
                        AssetDatabase.ImportAsset(localJSONAssetPath);
                        compilingFile.inkFile.jsonAsset = AssetDatabase.LoadAssetAtPath <TextAsset> (localJSONAssetPath);
                    }
                    if (warningsInEntireStory)
                    {
                        listOfFiles += " (With warning)";
                    }
                }
            }

            foreach (var compilingFile in InkLibrary.Instance.compilationStack)
            {
                if (OnCompileInk != null)
                {
                    OnCompileInk(compilingFile.inkFile);
                }
            }

            if (errorsFound)
            {
                Debug.LogWarning("Ink compilation completed with errors at " + DateTime.Now.ToLongTimeString() + listOfFiles);
            }
            else
            {
                Debug.Log("Ink compilation completed at " + DateTime.Now.ToLongTimeString() + listOfFiles);
            }
            InkLibrary.Instance.compilationStack.Clear();
            EditorUtility.ClearProgressBar();
            if (EditorApplication.isPlayingOrWillChangePlaymode)
            {
                Debug.LogWarning("Ink just finished recompiling while in play mode. Your runtime story may not be up to date.");
            }
            InkLibrary.Save();
        }
        void GetAndSetData(int i, Action onAllConvertersCompleted = null)
        {
            // This need to be in Init method
            // Need to get the assets that this converter is converting.
            // Need to return Name, Path, Initial info, Help link.
            // New empty list of ConverterItemInfos
            List<ConverterItemDescriptor> converterItemInfos = new List<ConverterItemDescriptor>();
            var initCtx = new InitializeConverterContext { items = converterItemInfos };

            var conv = m_CoreConvertersList[i];

            m_ConverterStates[i].isLoading = true;

            // This should also go to the init method
            // This will fill out the converter item infos list
            int id = i;
            conv.OnInitialize(initCtx, OnConverterCompleteDataCollection);

            void OnConverterCompleteDataCollection()
            {
                // Set the item infos list to to the right index
                m_ItemsToConvert[id] = converterItemInfos;
                m_ConverterStates[id].items = new List<ConverterItemState>(converterItemInfos.Count);

                // Default all the entries to true
                for (var j = 0; j < converterItemInfos.Count; j++)
                {
                    string message = string.Empty;
                    Status status;
                    bool active = true;
                    // If this data hasn't been filled in from the init phase then we can assume that there are no issues / warnings
                    if (string.IsNullOrEmpty(converterItemInfos[j].warningMessage))
                    {
                        status = Status.Pending;
                    }
                    else
                    {
                        status = Status.Warning;
                        message = converterItemInfos[j].warningMessage;
                        active = false;
                        m_ConverterStates[id].warnings++;
                    }

                    m_ConverterStates[id].items.Add(new ConverterItemState
                    {
                        isActive = active,
                        message = message,
                        status = status,
                        hasConverted = false,
                    });
                }

                m_ConverterStates[id].isLoading = false;
                m_ConverterStates[id].isInitialized = true;

                // Making sure that the pending amount is set to the amount of items needs converting
                m_ConverterStates[id].pending = m_ConverterStates[id].items.Count;

                EditorUtility.SetDirty(this);
                m_SerializedObject.ApplyModifiedProperties();

                CheckAllConvertersCompleted();

                // Make sure that the Convert Button is turned back on
                var button = rootVisualElement.Q<Button>("convertButton");
                button.SetEnabled(true);
            }

            void CheckAllConvertersCompleted()
            {
                int convertersToInitialize = 0;
                int convertersInitialized = 0;

                for (var j = 0; j < m_ConverterStates.Count; j++)
                {
                    var converter = m_ConverterStates[j];

                    // Skip inactive converters
                    if (!converter.isActiveAndEnabled)
                        continue;

                    if (converter.isInitialized)
                        convertersInitialized++;
                    else
                        convertersToInitialize++;
                }

                var sum = convertersToInitialize + convertersInitialized;

                Assert.IsFalse(sum == 0);

                // Show our progress so far
                EditorUtility.ClearProgressBar();
                EditorUtility.DisplayProgressBar($"Initializing converters", $"Initializing converters ({convertersInitialized}/{sum})...", (float)convertersInitialized / sum);

                // If all converters are initialized call the complete callback
                if (convertersToInitialize == 0)
                {
                    onAllConvertersCompleted?.Invoke();
                }
            }
        }
示例#28
0
        void ApplySettingsToTerrains(Terrain[] terrains, string errorContext = "")
        {
            int index = 0;

            try
            {
                bool continueEdit = true;

                // Only show this warning if the user has Mesh Settings enabled.
                if (m_Settings.EnableMeshResSettings)
                {
                    var newSize = new Vector3(m_Settings.TerrainWidth, m_Settings.TerrainHeight,
                                              m_Settings.TerrainLength);
                    foreach (var terrain in terrains)
                    {
                        // If any terrain has a size that's different from the specified settings, let's confirm
                        // the action.
                        if (terrain.terrainData.size != newSize)
                        {
                            var message =
                                "Some terrains have different sizes than the settings specified. This operation will resize the terrains potentially resulting in gaps and/or overlaps.";
                            if (string.IsNullOrEmpty(errorContext))
                            {
                                continueEdit = EditorUtility.DisplayDialog("Confirm",
                                                                           $"{message}\nAre you sure you want to continue?",
                                                                           "Continue", "Cancel");
                            }
                            else
                            {
                                continueEdit = EditorUtility.DisplayDialog("Confirm",
                                                                           $"1. {errorContext}\n2. {message}\n\nAre you sure you want to continue?",
                                                                           "Continue", "Cancel");
                            }
                            break;
                        }
                    }
                }

                if (continueEdit)
                {
                    foreach (var terrain in terrains)
                    {
                        EditorUtility.DisplayProgressBar("Applying settings changes on terrains",
                                                         string.Format("Updating terrain tile {0}", terrain.name),
                                                         ((float)index / terrains.Length));

                        if (m_Settings.EnableBasicSettings)
                        {
                            Undo.RecordObject(terrain, "Terrain property change");

                            terrain.groupingID           = m_Settings.GroupingID;
                            terrain.allowAutoConnect     = m_Settings.AutoConnect;
                            terrain.drawHeightmap        = m_Settings.DrawHeightmap;
                            terrain.drawInstanced        = m_Settings.DrawInstanced;
                            terrain.heightmapPixelError  = m_Settings.PixelError;
                            terrain.basemapDistance      = m_Settings.BaseMapDistance;
                            terrain.shadowCastingMode    = m_Settings.ShadowCastingMode;
                            terrain.materialTemplate     = m_Settings.MaterialTemplate;
                            terrain.reflectionProbeUsage = m_Settings.ReflectionProbeUsage;
#if UNITY_2019_2_OR_NEWER
#else
                            terrain.materialType = m_Settings.MaterialType;
                            if (m_Settings.MaterialType != Terrain.MaterialType.Custom)
                            {
                                terrain.legacySpecular  = m_Settings.LegacySpecular;
                                terrain.legacyShininess = m_Settings.LegacyShininess;
                            }
#endif
                        }

                        if (m_Settings.EnableMeshResSettings)
                        {
                            Undo.RecordObject(terrain.terrainData, "TerrainData property change");
                            Vector3 size = new Vector3(m_Settings.TerrainWidth, m_Settings.TerrainHeight,
                                                       m_Settings.TerrainLength);
                            terrain.terrainData.size = size;
                            terrain.terrainData.SetDetailResolution(m_Settings.DetailResolutaion,
                                                                    m_Settings.DetailResolutionPerPatch);
                        }

                        if (m_Settings.EnableTextureResSettings)
                        {
                            terrain.terrainData.baseMapResolution = m_Settings.BaseTextureResolution;
                            if (m_Settings.AlphaMapResolution != terrain.terrainData.alphamapResolution)
                            {
                                ToolboxHelper.ResizeControlTexture(terrain.terrainData, m_Settings.AlphaMapResolution);
                            }

                            if (m_Settings.HeightMapResolution != terrain.terrainData.heightmapResolution)
                            {
                                ToolboxHelper.ResizeHeightmap(terrain.terrainData, m_Settings.HeightMapResolution);
                            }
                        }

                        if (m_Settings.EnableTreeSettings)
                        {
                            Undo.RecordObject(terrain, "Terrain property change");

                            terrain.drawTreesAndFoliage         = m_Settings.DrawTreesAndFoliage;
                            terrain.bakeLightProbesForTrees     = m_Settings.BakeLightProbesForTrees;
                            terrain.deringLightProbesForTrees   = m_Settings.DeringLightProbesForTrees;
                            terrain.preserveTreePrototypeLayers = m_Settings.PreserveTreePrototypeLayers;
                            terrain.detailObjectDistance        = m_Settings.DetailObjectDistance;
                            terrain.collectDetailPatches        = m_Settings.CollectDetailPatches;
                            terrain.detailObjectDensity         = m_Settings.DetailObjectDensity;
                            terrain.treeDistance            = m_Settings.TreeDistance;
                            terrain.treeBillboardDistance   = m_Settings.TreeBillboardDistance;
                            terrain.treeCrossFadeLength     = m_Settings.TreeCrossFadeLength;
                            terrain.treeMaximumFullLODCount = m_Settings.TreeMaximumFullLODCount;
                        }

                        if (m_Settings.EnableWindSettings)
                        {
                            Undo.RecordObject(terrain.terrainData, "TerrainData property change");
                            terrain.terrainData.wavingGrassStrength = m_Settings.WavingGrassStrength;
                            terrain.terrainData.wavingGrassSpeed    = m_Settings.WavingGrassSpeed;
                            terrain.terrainData.wavingGrassAmount   = m_Settings.WavingGrassAmount;
                            terrain.terrainData.wavingGrassTint     = m_Settings.WavingGrassTint;
                        }

                        index++;
                    }
                }
            }
            finally
            {
                AssetDatabase.Refresh();
                EditorUtility.ClearProgressBar();
            }
        }
示例#29
0
        protected static void CheckForUpdates()
        {
            const string url = "https://github.com/GlitchEnzo/NuGetForUnity/releases";

#if UNITY_2017_1_OR_NEWER // UnityWebRequest is not available in Unity 5.2, which is the currently the earliest version supported by NuGetForUnity.
            using (UnityWebRequest request = UnityWebRequest.Get(url))
            {
                request.SendWebRequest();
#else
            using (WWW request = new WWW(url))
            {
#endif

                NugetHelper.LogVerbose("HTTP GET {0}", url);
                while (!request.isDone)
                {
                    EditorUtility.DisplayProgressBar("Checking updates", null, 0.0f);
                }
                EditorUtility.ClearProgressBar();

                string latestVersion            = null;
                string latestVersionDownloadUrl = null;

                string response = null;
#if UNITY_2017_1_OR_NEWER
                if (!request.isNetworkError && !request.isHttpError)
                {
                    response = request.downloadHandler.text;
                }
#else
                if (request.error == null)
                {
                    response = request.text;
                }
#endif

                if (response != null)
                {
                    latestVersion = GetLatestVersonFromReleasesHtml(response, out latestVersionDownloadUrl);
                }

                if (latestVersion == null)
                {
                    EditorUtility.DisplayDialog(
                        "Unable to Determine Updates",
                        string.Format("Couldn't find release information at {0}.", url),
                        "OK");
                    return;
                }

                NugetPackageIdentifier current = new NugetPackageIdentifier("NuGetForUnity", NugetPreferences.NuGetForUnityVersion);
                NugetPackageIdentifier latest  = new NugetPackageIdentifier("NuGetForUnity", latestVersion);
                if (current >= latest)
                {
                    EditorUtility.DisplayDialog(
                        "No Updates Available",
                        string.Format("Your version of NuGetForUnity is up to date.\nVersion {0}.", NugetPreferences.NuGetForUnityVersion),
                        "OK");
                    return;
                }

                // New version is available. Give user options for installing it.
                switch (EditorUtility.DisplayDialogComplex(
                            "Update Available",
                            string.Format("Current Version: {0}\nLatest Version: {1}", NugetPreferences.NuGetForUnityVersion, latestVersion),
                            "Install Latest",
                            "Open Releases Page",
                            "Cancel"))
                {
                case 0: Application.OpenURL(latestVersionDownloadUrl); break;

                case 1: Application.OpenURL(url); break;

                case 2: break;
                }
            }
        }
示例#30
0
        public static void AnalysisEffect()
        {
            s_AssetInfo.Clear();

            List <PrefabInfo>        prefabInfos = new List <PrefabInfo>();
            Dictionary <string, int> refCount    = new Dictionary <string, int>();

            string        path    = Application.dataPath + "/resources/effect/";
            List <string> files   = new List <string>();
            List <string> prefabs = new List <string>();

            PathUtils.GetFileList(ref files, path, true);
            PathUtils.GetFileListByEnds(ref files, ".prefab", ref prefabs);

            for (int i = 0; i < prefabs.Count; ++i)
            {
                string assets   = "/assets/";
                int    idx      = prefabs[i].ToLower().IndexOf(assets);
                int    startPos = idx + 1;// assets.Length;
                prefabs[i] = prefabs[i].Substring(startPos, prefabs[i].Length - startPos);
            }

            List <GameObject> allPrefab = new List <GameObject>();

            for (int i = 0; i < prefabs.Count; ++i)
            {
                EditorUtility.DisplayProgressBar("load prefab", "handle...", (float)i / prefabs.Count);

                GameObject prefab = AssetDatabase.LoadAssetAtPath(prefabs[i], typeof(GameObject)) as GameObject;
                allPrefab.Add(prefab);

                UnityEngine.Object[] roots      = new UnityEngine.Object[] { prefab };
                UnityEngine.Object[] dependObjs = EditorUtility.CollectDependencies(roots);

                PrefabInfo info = new PrefabInfo();
                info.name = prefabs[i];

                for (int k = 0; k < dependObjs.Length; ++k)
                {
                    string p = AssetDatabase.GetAssetPath(dependObjs[k]);
                    info.dependAsset.Add(p);

                    int count = 0;
                    if (dependObjs[k] == null)
                    {
                        continue;
                    }
                    if (refCount.TryGetValue(p, out count))
                    {
                        refCount[p] += 1;
                    }
                    else
                    {
                        refCount[p] = 1;
                    }
                }
                prefabInfos.Add(info);
            }
            EditorUtility.ClearProgressBar();

            UnityEngine.Object[] all           = allPrefab.ToArray();
            UnityEngine.Object[] allDependObjs = EditorUtility.CollectDependencies(all);
            for (int k = 0; k < allDependObjs.Length; ++k)
            {
                EditorUtility.DisplayProgressBar("foreach dependobjs", "handle...", (float)k / allDependObjs.Length);

                UnityEngine.Object obj = allDependObjs[k];
                string             p   = AssetDatabase.GetAssetPath(obj);

                MeshFilter meshFilter = obj as MeshFilter;
                if (meshFilter != null)
                {
                    Mesh     meshObj = meshFilter.sharedMesh;
                    MeshInfo info    = new MeshInfo();
                    info.name       = p;
                    info.meshFilter = meshFilter.name;
                    info.refCount   = refCount[p];
                    if (meshObj != null)
                    {
                        info.subMeshCount  = meshObj.subMeshCount;
                        info.vertexCount   = meshObj.vertexCount;
                        info.triangleCount = meshObj.triangles.Length;
                    }
                    s_AssetInfo.meshInfo.Add(info);
                }

                Texture2D texObj = obj as Texture2D;
                if (texObj != null)
                {
                    TextureInfo info = new TextureInfo();
                    info.name     = p;
                    info.refCount = refCount[p];
                    info.size.x   = texObj.width;
                    info.size.y   = texObj.height;
                    info.mipmap   = texObj.mipmapCount;
                    info.format   = texObj.format;
                    s_AssetInfo.textureInfo.Add(info);
                }

                Shader shaderObj = obj as Shader;
                if (shaderObj != null)
                {
                    ShaderInfo info = new ShaderInfo();
                    info.name     = p;
                    info.refCount = refCount[p];
                    s_AssetInfo.shaderInfo.Add(info);
                }
            }
            EditorUtility.ClearProgressBar();
            EditorUtility.UnloadUnusedAssetsImmediate();

            string outputFile = Application.dataPath + "AssetAnalysis.json";

            SerializeHelper.SaveToFile(s_AssetInfo, outputFile, true);


            {
                string fileName = Application.dataPath + "texture.csv";
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                FileStream   file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter sw   = new StreamWriter(file);
                string       line = "path,width,height,format,mipmap,refCount";
                sw.WriteLine(line);
                for (int i = 0; i < s_AssetInfo.textureInfo.Count; ++i)
                {
                    TextureInfo info = s_AssetInfo.textureInfo[i];
                    //if(info.size.x > 128 || info.size.y > 128)
                    {
                        line = info.name + "," + info.size.x + "," + info.size.y + "," + info.format.ToString() + "," + info.mipmap + "," + info.refCount;
                        sw.WriteLine(line);
                    }
                }

                sw.Flush();
                file.Flush();
                file.Close();
            }

            Debug.Log("分析完毕!");
        }