Exemple #1
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            //EditorGUI.PropertyField(position, property, label);

            var attr = this.attr;
            var go   = (property.serializedObject.targetObject as Component).gameObject;

            if (go == null)
            {
                return;
            }

            var pth = AssetDatabase.GetAssetPath(go);

            if (string.IsNullOrEmpty(pth) == true)
            {
                return;
            }

            var assetPath = System.IO.Path.GetDirectoryName(pth);

            assetPath      = assetPath.Replace("/Screens", "/Layouts");
            attr.filterDir = assetPath;

            var target = property;

            EditorGUI.LabelField(position, label);
            position.x     += EditorGUIUtility.labelWidth;
            position.width -= EditorGUIUtility.labelWidth;

            if (EditorGUI.DropdownButton(position, new GUIContent(target.objectReferenceValue != null ? EditorHelpers.StringToCaption(target.objectReferenceValue.name) : attr.noneOption), FocusType.Passive) == true)
            {
                var rect   = position;
                var vector = GUIUtility.GUIToScreenPoint(new Vector2(rect.x, rect.y));
                rect.x = vector.x;
                rect.y = vector.y;

                var popup = new Popup()
                {
                    title = attr.menuName, autoClose = true, screenRect = new Rect(rect.x, rect.y + rect.height, rect.width, 200f)
                };
                var objects = AssetDatabase.FindAssets("t:" + (attr.filterType != null ? attr.filterType : "Object"), attr.filterDir == null ? null : new [] { attr.filterDir });

                var allObjects = Resources.LoadAll <GameObject>("").Where(x => x.GetComponent <WindowLayout>() != null && x.GetComponent <TemplateMarker>() != null).ToArray();
                for (int i = 0; i < allObjects.Length; ++i)
                {
                    var idx = i;
                    popup.Item("Clone Template/" + allObjects[i].name, null, searchable: true, action: (item) => {
                        var p       = AssetDatabase.GetAssetPath(allObjects[idx]);
                        var newPath = AssetDatabase.GenerateUniqueAssetPath(assetPath + "/" + allObjects[idx].name + ".prefab");
                        AssetDatabase.CopyAsset(p, newPath);
                        AssetDatabase.ImportAsset(newPath, ImportAssetOptions.ForceUpdate);
                        var newGo = AssetDatabase.LoadAssetAtPath <GameObject>(newPath);
                        Object.DestroyImmediate(newGo.GetComponent <TemplateMarker>(), true);

                        property.serializedObject.Update();
                        target.objectReferenceValue = newGo.GetComponent <WindowLayout>();
                        property.serializedObject.ApplyModifiedProperties();
                    }, order: -1);
                }

                if (string.IsNullOrEmpty(attr.noneOption) == false)
                {
                    popup.Item(attr.noneOption, null, searchable: false, action: (item) => {
                        property.serializedObject.Update();
                        target.objectReferenceValue = null;
                        property.serializedObject.ApplyModifiedProperties();
                    }, order: -1);
                }

                for (int i = 0; i < objects.Length; ++i)
                {
                    var path  = AssetDatabase.GUIDToAssetPath(objects[i]);
                    var asset = AssetDatabase.LoadAssetAtPath <GameObject>(path);
                    if (asset.GetComponent <WindowLayout>() == null)
                    {
                        continue;
                    }

                    popup.Item(EditorHelpers.StringToCaption(asset.name), () => {
                        property.serializedObject.Update();
                        target.objectReferenceValue = asset.GetComponent <WindowLayout>();
                        property.serializedObject.ApplyModifiedProperties();
                    });
                }
                popup.Show();
            }
        }
Exemple #2
0
        public static void SetupPostProcessing()
        {
#if UNITY_POST_PROCESSING_STACK_V2 && UNITY_2018_3_OR_NEWER
            const string defaultName = "WeatherMakerPostProcessingProfile_Default";
            string[]     assets      = AssetDatabase.FindAssets("WeatherMakerPrefab");
            foreach (string asset in assets)
            {
                string path = AssetDatabase.GUIDToAssetPath(asset);
                if (path.EndsWith("WeatherMakerPrefab.prefab", StringComparison.OrdinalIgnoreCase))
                {
                    string dir         = Path.GetDirectoryName(path);
                    string profilesDir = Path.Combine(dir, "Profiles");
                    profilesDir = Path.Combine(profilesDir, "PostProcessing");
                    string assetPath = Path.Combine(profilesDir, defaultName + ".asset");
                    Directory.CreateDirectory(profilesDir);
                    PostProcessProfile profile = AssetDatabase.LoadAssetAtPath <PostProcessProfile>(assetPath);

                    if (profile == null)
                    {
                        EditorUtility.DisplayDialog("Error", "Unable to find Weather Maker default post processing profile at '" + assetPath + "'", "OK");
                        return;

                        /*
                         * profile = ScriptableObject.CreateInstance<PostProcessProfile>();
                         * profile.name = defaultName;
                         * AmbientOcclusion ambient = profile.AddSettings<AmbientOcclusion>();
                         * ambient.intensity = new FloatParameter { value = 0.5f, overrideState = true };
                         * Bloom bloom = profile.AddSettings<Bloom>();
                         * bloom.intensity = new FloatParameter { value = 3.0f, overrideState = true };
                         * ColorGrading color = profile.AddSettings<ColorGrading>();
                         * color.tonemapper = new TonemapperParameter { value = Tonemapper.ACES, overrideState = true };
                         * color.postExposure = new FloatParameter { value = 0.7f, overrideState = true };
                         * DepthOfField df = profile.AddSettings<DepthOfField>();
                         * df.focusDistance = new FloatParameter { value = 3.5f, overrideState = true };
                         * Vignette vig = profile.AddSettings<Vignette>();
                         * vig.intensity = new FloatParameter { value = 0.3f, overrideState = true };
                         *
                         * if (createProfile)
                         * {
                         *  AssetDatabase.CreateAsset(profile, assetPath);
                         *  AssetDatabase.SaveAssets();
                         *  AssetDatabase.Refresh();
                         *  EditorUtility.FocusProjectWindow();
                         * }
                         */
                    }

                    Camera cam = Camera.main;
                    if (cam == null)
                    {
                        EditorUtility.DisplayDialog("Error", "Could not find main camera in scene, make sure your camera is tagged as main camera", "OK");
                        return;
                    }

                    PostProcessLayer layer = cam.GetComponent <PostProcessLayer>();
                    if (layer == null)
                    {
                        layer = Undo.AddComponent <PostProcessLayer>(cam.gameObject);
                    }
                    layer.antialiasingMode = PostProcessLayer.Antialiasing.SubpixelMorphologicalAntialiasing;
                    layer.fog = new Fog {
                        enabled = false, excludeSkybox = true
                    };
                    layer.volumeLayer = -1;

                    PostProcessVolume volume = cam.GetComponent <PostProcessVolume>();
                    if (volume == null)
                    {
                        volume = Undo.AddComponent <PostProcessVolume>(cam.gameObject);
                    }
                    volume.sharedProfile = profile;
                    volume.isGlobal      = true;
                    Undo.RegisterCompleteObjectUndo(layer, "Weather Maker Add Post Processing Volume");

                    Selection.activeObject = cam.gameObject;

                    EditorUtility.DisplayDialog("Success", "Post processing profile created at '" + defaultName + "' and applied to main camera. " +
                                                "You should configure your layer on the camera and post processing for best performance.", "OK");

                    return;
                }
            }

            EditorUtility.DisplayDialog("Error", "There was an error setting up the post processing stack, please do it manually", "OK");
#else
            EditorUtility.DisplayDialog("Error", "Please use Unity 2018.3 or newer and use the package manager to add the post processing stack v2. " +
                                        "Also be sure 'UNITY_POST_PROCESSING_STACK_V2' is in player settings -> scripting defines. Do all this and try again.", "OK");
#endif
        }
Exemple #3
0
        private bool ProcessScenes()
        {
            var scenePaths =
                AssetDatabase.FindAssets("t:Scene")
                .Select(n => AssetDatabase.GUIDToAssetPath(n))
                .ToList();

            bool hasDirtyScenes = false;

            for (int i = 0; i < EditorSceneManager.sceneCount; i++)
            {
                if (EditorSceneManager.GetSceneAt(i).isDirty)
                {
                    hasDirtyScenes = true;
                    break;
                }
            }

            if (hasDirtyScenes && !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                return(false);
            }

            var oldSceneSetup = EditorSceneManager.GetSceneManagerSetup();

            try
            {
                for (int i = 0; i < scenePaths.Count; i++)
                {
                    var scenePath = scenePaths[i];

                    if (EditorUtility.DisplayCancelableProgressBar("Scanning Scenes", "Scene " + (i + 1) + "/" + scenePaths.Count + " - " + scenePath, (float)i / scenePaths.Count))
                    {
                        return(false);
                    }

                    EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);

                    var sceneGOs = UnityEngine.Object.FindObjectsOfType <GameObject>();

                    foreach (var go in sceneGOs)
                    {
                        if ((go.hideFlags & HideFlags.DontSaveInBuild) == 0)
                        {
                            foreach (var component in go.GetComponents <ISerializationCallbackReceiver>())
                            {
                                component.OnBeforeSerialize();

                                var prefabSupporter = component as ISupportsPrefabSerialization;

                                if (prefabSupporter != null)
                                {
                                    // Also force a serialization of the object's prefab modifications, in case there are unknown types in there

                                    List <UnityEngine.Object> objs = null;
                                    var mods = UnitySerializationUtility.DeserializePrefabModifications(prefabSupporter.SerializationData.PrefabModifications, prefabSupporter.SerializationData.PrefabModificationsReferencedUnityObjects);
                                    UnitySerializationUtility.SerializePrefabModifications(mods, ref objs);
                                }
                            }
                        }
                    }
                }

                // Load a new empty scene that will be unloaded immediately, just to be sure we completely clear all changes made by the scan
                EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
            }
            finally
            {
                try
                {
                    if (oldSceneSetup != null && oldSceneSetup.Length > 0)
                    {
                        EditorUtility.DisplayProgressBar("Restoring scene setup", "", 0.5f);
                        EditorSceneManager.RestoreSceneManagerSetup(oldSceneSetup);
                    }
                }
                finally
                {
                    EditorUtility.ClearProgressBar();
                }
            }

            return(true);
        }
        public void ResetToDefaults()
        {
            UndoHandler.RegisterUndoableAction(this, "Reset To Defaults");

                        #if UNITY_EDITOR          // in UnityEditor use Presets or EditorJsonUtility
                        #if UNITY_2018_1_OR_NEWER // Presets were introduced in Unity 2018.1
                        #if UNITY_2019_3_OR_NEWER // GetDefaultForObject became obsolete in Unity 2019.3
            var presets = Preset.GetDefaultPresetsForObject(this);
            var preset  = presets.Length > 0 ? presets[0] : null;
                        #else
            var preset = Preset.GetDefaultForObject(this);
                        #endif

            // if no default preset has been assigned for preferences asset, then try finding a preset
            // in the same directory with the preferences asset
            if (preset == null)
            {
                var preferencesPath = AssetDatabase.GetAssetPath(this);
                var directoryPath   = FileUtility.GetParentDirectory(preferencesPath);
                var updateGuids     = AssetDatabase.FindAssets("t:Preset", ArrayExtensions.TempStringArray(directoryPath));
                for (int n = updateGuids.Length - 1; n >= 0; n--)
                {
                    var path = AssetDatabase.GUIDToAssetPath(updateGuids[n]);
                    preset = AssetDatabase.LoadAssetAtPath <Preset>(path);
                    if (!string.Equals(preset.GetTargetFullTypeName(), typeof(InspectorPreferences).FullName, StringComparison.OrdinalIgnoreCase))
                    {
                        preset = null;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            if (preset != null)
            {
                preset.ApplyTo(this);
            }
            else
                        #endif
            {
                var freshInstance = CreateInstance <InspectorPreferences>();
                var jsonString    = EditorJsonUtility.ToJson(freshInstance);
                Platform.Active.Destroy(freshInstance);
                EditorJsonUtility.FromJsonOverwrite(jsonString, this);
            }
                        #else
            // at runtime use JsonUtility to reset values to those of a freshly created instance
            var freshInstance = CreateInstance <InspectorPreferences>();
            var jsonString    = JsonUtility.ToJson(freshInstance);
            Platform.Active.Destroy(freshInstance);
            JsonUtility.FromJsonOverwrite(jsonString, this);
                        #endif

            setupDone         = false;
            isFirstOnValidate = true;

            if (Event.current != null)
            {
                Setup();
            }

            Platform.Active.SetDirty(this);

            if (onSettingsChanged != null)
            {
                onSettingsChanged(this);
            }
        }
Exemple #5
0
        /// <summary>
        /// Enable the latest VersionHandler DLL if it's not already loaded.
        /// </summary>
        private static void BootStrap()
        {
            var bootStrapping = BootStrapping;
            var implAvailable = Impl != null;

            // If the VersionHandler assembly is already loaded or we're still bootstrapping we have
            // nothing to do.
            if (bootStrapping)
            {
                BootStrapping = !implAvailable;
                return;
            }
            EditorApplication.update -= BootStrap;
            if (implAvailable)
            {
                return;
            }

            var assemblies = new List <Match>();

            foreach (string assetGuid in AssetDatabase.FindAssets("l:gvh"))
            {
                string filename = AssetDatabase.GUIDToAssetPath(assetGuid);
                var    match    = VERSION_HANDLER_FILENAME_RE.Match(filename);
                if (match.Success)
                {
                    assemblies.Add(match);
                }
            }
            if (assemblies.Count == 0)
            {
                UnityEngine.Debug.LogWarning(String.Format("No {0} DLL found to bootstrap",
                                                           VERSION_HANDLER_ASSEMBLY_NAME));
                return;
            }
            // Sort assembly paths by version number.
            string mostRecentAssembly      = null;
            var    mostRecentVersionNumber = -1;

            foreach (var match in assemblies)
            {
                var filename = match.Groups[0].Value;
                var version  = match.Groups[2].Value;
                // Convert a multi-component version number to a string.
                var components = version.Split(new [] { '.' });
                Array.Reverse(components);
                var versionNumber              = 0;
                var componentMultiplier        = 1000;
                var currentComponentMultiplier = 1;
                foreach (var component in components)
                {
                    try {
                        versionNumber += Int32.Parse(component) * currentComponentMultiplier;
                    } catch (FormatException) {
                        // Ignore the component.
                    }
                    currentComponentMultiplier *= componentMultiplier;
                }
                if (versionNumber > mostRecentVersionNumber)
                {
                    mostRecentVersionNumber = versionNumber;
                    mostRecentAssembly      = filename;
                }
            }
            if (String.IsNullOrEmpty(mostRecentAssembly))
            {
                UnityEngine.Debug.LogWarning(String.Format("Failed to get the most recent {0} DLL.  " +
                                                           "Unable to bootstrap.",
                                                           VERSION_HANDLER_ASSEMBLY_NAME));
                return;
            }
            BootStrapping = true;
            if (VersionHandler.FindClass("UnityEditor", "UnityEditor.PluginImporter") != null)
            {
                EnableEditorPlugin(mostRecentAssembly);
            }
            else
            {
                ReimportPlugin(mostRecentAssembly);
            }
        }
Exemple #6
0
        public void Audit(Action <ProjectIssue> onIssueFound, Action onComplete, IProgressBar progressBar = null)
        {
            var id = k_ShaderVariantFirstId;

            if (s_ShaderVariantData == null)
            {
                var descriptor = new ProblemDescriptor
                                 (
                    id,
                    "Shader analysis incomplete",
                    Area.BuildSize,
                    string.Empty,
                    string.Empty
                                 );

                var message = "Build the project and run Project Auditor analysis";
#if !UNITY_2018_2_OR_NEWER
                message = "This feature requires Unity 2018";
#endif
                var issue = new ProjectIssue(descriptor, message, IssueCategory.Shaders);
                issue.SetCustomProperties(new[] { string.Empty, string.Empty });
                onIssueFound(issue);
                onComplete();
                return;
            }

            var shaderPathMap = new Dictionary <string, string>();
            var shaderGuids   = AssetDatabase.FindAssets("t:shader");
            foreach (var guid in shaderGuids)
            {
                var assetPath = AssetDatabase.GUIDToAssetPath(guid);
                var shader    = AssetDatabase.LoadMainAssetAtPath(assetPath) as Shader;

                shaderPathMap.Add(shader.name, assetPath);
            }

            foreach (var keyPair in s_ShaderVariantData)
            {
                var shader         = keyPair.Key;
                var shaderVariants = keyPair.Value;

                var shaderName = shader.name;
                var descriptor = new ProblemDescriptor
                                 (
                    id++,
                    shaderName,
                    Area.BuildSize,
                    string.Empty,
                    string.Empty
                                 );

                string assetPath;
                if (shaderPathMap.ContainsKey(shaderName))
                {
                    assetPath = shaderPathMap[shaderName];
                }
                else
                {
                    // built-in shader
                    assetPath = AssetDatabase.GetAssetPath(shader);
                }

                foreach (var shaderVariantData in shaderVariants)
                {
                    var compilerData     = shaderVariantData.compilerData;
                    var shaderKeywordSet = compilerData.shaderKeywordSet.GetShaderKeywords().ToArray();

#if UNITY_2019_3_OR_NEWER
                    var keywords = shaderKeywordSet.Select(keyword => ShaderKeyword.IsKeywordLocal(keyword) ?  ShaderKeyword.GetKeywordName(shader, keyword) : ShaderKeyword.GetGlobalKeywordName(keyword)).ToArray();
#else
                    var keywords = shaderKeywordSet.Select(keyword => keyword.GetKeywordName()).ToArray();
#endif
                    var keywordString = String.Join(", ", keywords);
                    if (string.IsNullOrEmpty(keywordString))
                    {
                        keywordString = "<no keywords>";
                    }

                    var issue = new ProjectIssue(descriptor, shaderName, IssueCategory.Shaders, new Location(assetPath));
                    issue.SetCustomProperties(new[]
                    {
                        compilerData.shaderCompilerPlatform.ToString(),
                        shaderVariantData.passName,
                        keywordString,
                    });

                    onIssueFound(issue);
                }
            }

            onComplete();
        }
Exemple #7
0
        private void NotifyAssetPostprocessorGraphs(AssetPostprocessorContext ctx)
        {
            var guids = AssetDatabase.FindAssets(Model.Settings.GRAPH_SEARCH_CONDITION);

            var executingGraphs = new List <Model.ConfigGraph> ();

            foreach (var guid in guids)
            {
                string path  = AssetDatabase.GUIDToAssetPath(guid);
                var    graph = AssetDatabase.LoadAssetAtPath <Model.ConfigGraph>(path);
                if (graph != null && graph.UseAsAssetPostprocessor)
                {
                    bool isAnyNodeAffected = false;
                    foreach (var n in graph.Nodes)
                    {
                        isAnyNodeAffected |= n.Operation.Object.OnAssetsReimported(n, null, EditorUserBuildSettings.activeBuildTarget, ctx, true);
                    }
                    if (isAnyNodeAffected)
                    {
                        executingGraphs.Add(graph);
                    }
                }
            }

            if (executingGraphs.Count > 0)
            {
                if (executingGraphs.Count > 1)
                {
                    executingGraphs.Sort((l, r) => l.ExecuteOrderPriority - r.ExecuteOrderPriority);
                }

                float          currentCount            = 0f;
                float          totalCount              = (float)executingGraphs.Sum(g => g.Nodes.Count);
                Model.NodeData lastNode                = null;
                float          graphStartTime          = Time.realtimeSinceStartup;
                bool           progressbarDisplayed    = false;
                float          progressBarShowDelaySec = 0.3f;

                Action <Model.NodeData, string, float> updateHandler = (node, message, progress) => {
                    if (lastNode != node)
                    {
                        // do not add count on first node visit to
                        // calcurate percantage correctly
                        if (lastNode != null)
                        {
                            ++currentCount;
                        }
                        lastNode = node;

                        if (!progressbarDisplayed)
                        {
                            if (Time.realtimeSinceStartup - graphStartTime > progressBarShowDelaySec)
                            {
                                progressbarDisplayed = true;
                            }
                        }
                    }

                    if (progressbarDisplayed)
                    {
                        var graphName = GetCurrentGraphController().TargetGraph.GetGraphName();

                        float currentNodeProgress  = progress * (1.0f / totalCount);
                        float currentTotalProgress = (currentCount / totalCount) + currentNodeProgress;

                        string title = string.Format("Building {2}[{0}/{1}]", currentCount, totalCount, graphName);
                        string info  = $"Processing {node.Name}:{message}";

                        EditorUtility.DisplayProgressBar(title, info, currentTotalProgress);
                    }
                };

                foreach (var g in executingGraphs)
                {
                    AssetGraphUtility.ExecuteGraph(g, false, updateHandler);
                }

                if (progressbarDisplayed)
                {
                    EditorUtility.ClearProgressBar();
                }

                AssetDatabase.Refresh();
            }
        }
Exemple #8
0
        static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            Profiler.BeginSample("VFXShaderGraphPostProcessor");

            try
            {
                var modifiedShaderGraphs = new HashSet <ShaderGraphVfxAsset>();

                foreach (var asset in importedAssets.Concat(deletedAssets))
                {
                    if (asset.EndsWith(".shadergraph", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var ass = AssetDatabase.LoadAssetAtPath <ShaderGraphVfxAsset>(asset);
                        if (ass != null)
                        {
                            modifiedShaderGraphs.Add(ass);
                        }
                    }
                }

                if (modifiedShaderGraphs.Count > 0)
                {
                    string[] guids            = AssetDatabase.FindAssets("t:VisualEffectAsset");
                    var      assetsToReimport = new HashSet <VFXGraph>();

                    foreach (var vfxPath in guids.Select(t => AssetDatabase.GUIDToAssetPath(t)))
                    {
                        var resource = VisualEffectResource.GetResourceAtPath(vfxPath);
                        if (resource != null)
                        {
                            VFXGraph graph = resource.GetOrCreateGraph();

                            if (graph != null)
                            {
                                if (graph.children.OfType <VFXShaderGraphParticleOutput>().Any(t => modifiedShaderGraphs.Contains(t.shaderGraph)))
                                {
                                    assetsToReimport.Add(graph);
                                }
                            }
                        }
                    }

                    foreach (var graph in assetsToReimport)
                    {
                        foreach (var sgOutput in graph.children.OfType <VFXShaderGraphParticleOutput>().Where(t => modifiedShaderGraphs.Contains(t.shaderGraph)))
                        {
                            int instanceID = sgOutput.shaderGraph.GetInstanceID();

                            // This is needed because the imported invalidate the object
                            sgOutput.shaderGraph = EditorUtility.InstanceIDToObject(instanceID) as ShaderGraphVfxAsset;

                            sgOutput.ResyncSlots(true);
                        }

                        graph.SetExpressionGraphDirty();
                        graph.RecompileIfNeeded();
                    }
                }

                // Update currently edited VFX mesh outputs if needed
                var currentGraph = VFXViewWindow.currentWindow?.graphView?.controller?.graph;
                if (currentGraph)
                {
                    var meshData = currentGraph.children.OfType <VFXStaticMeshOutput>().Select(o => (VFXDataMesh)(o.GetData()));
                    if (meshData.Any())
                    {
                        foreach (var asset in importedAssets.Concat(deletedAssets))
                        {
                            if (asset.EndsWith(".shadergraph", StringComparison.InvariantCultureIgnoreCase) || asset.EndsWith(".shader", StringComparison.InvariantCultureIgnoreCase))
                            {
                                var shader = AssetDatabase.LoadAssetAtPath <Shader>(asset);
                                foreach (var data in meshData)
                                {
                                    if (data.shader == shader)
                                    {
                                        data.RefreshShader();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                Profiler.EndSample();
            }
        }
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var currentTime = DateTime.Now.Ticks;

            if (ctx.assetPath != path)
            {
                ctx.LogImportError("The sgpostsubgraph extension may only be used internally by Shader Graph.");
                return;
            }

            if (SubGraphDatabase.instance == null)
            {
                SubGraphDatabase.instance = ScriptableObject.CreateInstance <SubGraphDatabase>();
            }
            var database = SubGraphDatabase.instance;

            var allSubGraphGuids = AssetDatabase.FindAssets($"t:{nameof(SubGraphAsset)}").ToList();

            allSubGraphGuids.Sort();
            var subGraphMap  = new Dictionary <string, SubGraphData>();
            var graphDataMap = new Dictionary <string, GraphData>();

            foreach (var subGraphData in database.subGraphs)
            {
                if (allSubGraphGuids.BinarySearch(subGraphData.assetGuid) >= 0)
                {
                    subGraphMap.Add(subGraphData.assetGuid, subGraphData);
                }
            }

            var dirtySubGraphGuids = new List <string>();

            foreach (var subGraphGuid in allSubGraphGuids)
            {
                var subGraphAsset = AssetDatabase.LoadAssetAtPath <SubGraphAsset>(AssetDatabase.GUIDToAssetPath(subGraphGuid));
                if (!subGraphMap.TryGetValue(subGraphGuid, out var subGraphData))
                {
                    subGraphData = new SubGraphData();
                }

                if (subGraphAsset.importedAt > subGraphData.processedAt)
                {
                    dirtySubGraphGuids.Add(subGraphGuid);
                    subGraphData.Reset();
                    subGraphData.processedAt = currentTime;
                    var subGraphPath = AssetDatabase.GUIDToAssetPath(subGraphGuid);
                    var textGraph    = File.ReadAllText(subGraphPath, Encoding.UTF8);
                    var graphData    = new GraphData {
                        isSubGraph = true, assetGuid = subGraphGuid
                    };
                    JsonUtility.FromJsonOverwrite(textGraph, graphData);
                    subGraphData.children.AddRange(graphData.GetNodes <SubGraphNode>().Select(x => x.subGraphGuid).Distinct());
                    subGraphData.assetGuid     = subGraphGuid;
                    subGraphMap[subGraphGuid]  = subGraphData;
                    graphDataMap[subGraphGuid] = graphData;
                }
                else
                {
                    subGraphData.ancestors.Clear();
                    subGraphData.descendents.Clear();
                    subGraphData.isRecursive = false;
                }
            }

            database.subGraphs.Clear();
            database.subGraphs.AddRange(subGraphMap.Values);
            database.subGraphs.Sort((s1, s2) => s1.assetGuid.CompareTo(s2.assetGuid));
            database.subGraphGuids.Clear();
            database.subGraphGuids.AddRange(database.subGraphs.Select(x => x.assetGuid));

            var permanentMarks = new HashSet <string>();
            var stack          = new Stack <string>(allSubGraphGuids.Count);

            // Detect recursion, and populate `ancestors` and `descendents` per sub graph.
            foreach (var rootSubGraphData in database.subGraphs)
            {
                var rootSubGraphGuid = rootSubGraphData.assetGuid;
                stack.Push(rootSubGraphGuid);
                while (stack.Count > 0)
                {
                    var subGraphGuid = stack.Pop();
                    if (!permanentMarks.Add(subGraphGuid))
                    {
                        continue;
                    }

                    var subGraphData = subGraphMap[subGraphGuid];
                    if (subGraphData != rootSubGraphData)
                    {
                        subGraphData.ancestors.Add(rootSubGraphGuid);
                        rootSubGraphData.descendents.Add(subGraphGuid);
                    }
                    foreach (var childSubGraphGuid in subGraphData.children)
                    {
                        if (childSubGraphGuid == rootSubGraphGuid)
                        {
                            rootSubGraphData.isRecursive = true;
                        }
                        else if (subGraphMap.ContainsKey(childSubGraphGuid))
                        {
                            stack.Push(childSubGraphGuid);
                        }
                    }
                }
                permanentMarks.Clear();
            }

            // Next up we build a list of sub graphs to be processed, which will later be sorted topologically.
            var sortedSubGraphs = new List <SubGraphData>();

            foreach (var subGraphGuid in dirtySubGraphGuids)
            {
                var subGraphData = subGraphMap[subGraphGuid];
                if (permanentMarks.Add(subGraphGuid))
                {
                    sortedSubGraphs.Add(subGraphData);
                }

                // Note that we're traversing up the graph via ancestors rather than descendents, because all Sub Graphs using the current sub graph needs to be re-processed.
                foreach (var ancestorGuid in subGraphData.ancestors)
                {
                    if (permanentMarks.Add(ancestorGuid))
                    {
                        var ancestorSubGraphData = subGraphMap[ancestorGuid];
                        sortedSubGraphs.Add(ancestorSubGraphData);
                    }
                }
            }
            permanentMarks.Clear();

            // Sort topologically. At this stage we can assume there are no loops because all recursive sub graphs have been filtered out.
            sortedSubGraphs.Sort((s1, s2) => s1.descendents.Contains(s2.assetGuid) ? 1 : s2.descendents.Contains(s1.assetGuid) ? -1 : 0);

            // Finally process the topologically sorted sub graphs without recursion.
            var registry       = new FunctionRegistry(new ShaderStringBuilder(), true);
            var messageManager = new MessageManager();

            foreach (var subGraphData in sortedSubGraphs)
            {
                try
                {
                    var subGraphPath = AssetDatabase.GUIDToAssetPath(subGraphData.assetGuid);
                    if (!graphDataMap.TryGetValue(subGraphData.assetGuid, out var graphData))
                    {
                        var textGraph = File.ReadAllText(subGraphPath, Encoding.UTF8);
                        graphData = new GraphData {
                            isSubGraph = true, assetGuid = subGraphData.assetGuid
                        };
                        JsonUtility.FromJsonOverwrite(textGraph, graphData);
                    }

                    graphData.messageManager = messageManager;
                    ProcessSubGraph(subGraphMap, registry, subGraphData, graphData);
                    if (messageManager.nodeMessagesChanged)
                    {
                        var subGraphAsset = AssetDatabase.LoadAssetAtPath <SubGraphAsset>(AssetDatabase.GUIDToAssetPath(subGraphData.assetGuid));
                        foreach (var pair in messageManager.GetNodeMessages())
                        {
                            var node = graphData.GetNodeFromTempId(pair.Key);
                            foreach (var message in pair.Value)
                            {
                                MessageManager.Log(node, subGraphPath, message, subGraphAsset);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    subGraphData.isValid = false;
                    var subGraphAsset = AssetDatabase.LoadAssetAtPath <SubGraphAsset>(AssetDatabase.GUIDToAssetPath(subGraphData.assetGuid));
                    Debug.LogException(e, subGraphAsset);
                }
                finally
                {
                    subGraphData.processedAt = currentTime;
                    messageManager.ClearAll();
                }
            }

            // Carry over functions used by sub-graphs that were not re-processed in this import.
            foreach (var subGraphData in database.subGraphs)
            {
                foreach (var functionName in subGraphData.functionNames)
                {
                    if (!registry.sources.ContainsKey(functionName))
                    {
                        registry.sources.Add(functionName, database.functionSources[database.functionNames.BinarySearch(functionName)]);
                    }
                }
            }

            var functions = registry.sources.ToList();

            functions.Sort((p1, p2) => p1.Key.CompareTo(p2.Key));
            database.functionNames.Clear();
            database.functionSources.Clear();
            foreach (var pair in functions)
            {
                database.functionNames.Add(pair.Key);
                database.functionSources.Add(pair.Value);
            }

            ctx.AddObjectToAsset("MainAsset", database);
            ctx.SetMainObject(database);

            SubGraphDatabase.instance = null;
        }
    public static void OnSpriteSelection(Sprite pSelectedSprite, ObjectField pField)
    {
        if (pSelectedSprite == null)
        {
            return;
        }
        string[] aAssetFolder = { "Assets/ScriptableObjects/Asset Meta Data" };
        if (!AssetDatabase.IsValidFolder(aAssetFolder[0]))
        {
            ShowSelectionWarning();
            ResetSpriteSelection(pField);
            return;
        }
        string[] aAssetGUIDs = AssetDatabase.FindAssets(pSelectedSprite.texture.name, aAssetFolder);
        if (aAssetGUIDs.Length > 0)
        {
            string aPath = AssetDatabase.GUIDToAssetPath(aAssetGUIDs[0]);
            if (AssetDatabase.GetMainAssetTypeAtPath(aPath) == typeof(AssetMetaData))
            {
                AssetMetaData aCurrentAssetData = (AssetMetaData)AssetDatabase.LoadAssetAtPath(aPath, typeof(AssetMetaData));
                if (aCurrentAssetData.mType == AssetMetaData.AssetType.TextureAsset)
                {
                    switch (GameObjectEditor.GetCurrentScriptable().mType)
                    {
                    case GameScriptable.ObjectType.SpawnFactory:
                        SpawnFactory aTempObj = (SpawnFactory)GameObjectEditor.GetCurrentScriptable();
                        aTempObj.mTextureGUID   = aCurrentAssetData.mGUID;
                        aTempObj.mDisplaySprite = pSelectedSprite;
                        break;

                    case GameScriptable.ObjectType.StaticObject:
                        StaticObject aTObj = (StaticObject)GameObjectEditor.GetCurrentScriptable();
                        aTObj.mTextureGUID   = aCurrentAssetData.mGUID;
                        aTObj.mDisplaySprite = pSelectedSprite;
                        break;

                    case GameScriptable.ObjectType.Item:
                        Item aTmpObj = (Item)GameObjectEditor.GetCurrentScriptable();
                        aTmpObj.mTextureGUID   = aCurrentAssetData.mGUID;
                        aTmpObj.mDisplaySprite = pSelectedSprite;
                        break;

                    default:
                        ShowSelectionWarning();
                        ResetSpriteSelection(pField);
                        break;
                    }
                }
                else
                {
                    ShowSelectionWarning();
                    ResetSpriteSelection(pField);
                    return;
                }
            }
            else
            {
                ShowSelectionWarning();
                ResetSpriteSelection(pField);
                return;
            }
        }
        else
        {
            ShowSelectionWarning();
            ResetSpriteSelection(pField);
            return;
        }
    }
Exemple #11
0
 public void OnEnable()
 {
     scenesInAssetDatabase = AssetDatabase.FindAssets("t:Scene")
                             .Select(AssetDatabase.GUIDToAssetPath)
                             .Select(AssetDatabase.LoadAssetAtPath <SceneAsset>).ToArray();
 }
Exemple #12
0
        public void LoadData()
        {
            // Build TypeByModuleInfo and ModuleInfoByInput dictionaries
            TypeByModuleInfo.Clear();
            ModuleInfoByInput.Clear();
            TypeByModuleInfo = new SortedDictionary <ModuleInfoAttribute, System.Type>(typeof(CGModule).GetAllTypesWithAttribute <ModuleInfoAttribute>());

            foreach (var kv in TypeByModuleInfo)
            {
                var T      = kv.Value;
                var fields = T.GetFields(BindingFlags.Public | BindingFlags.Instance);
                foreach (var f in fields)
                {
                    if (f.FieldType == typeof(CGModuleInputSlot))
                    {
                        var slotAttrib = f.GetCustomAttributes(typeof(InputSlotInfo), true);
                        if (slotAttrib.Length > 0)
                        {
                            var si = (InputSlotInfo)slotAttrib[0];
                            List <ModuleInfoAttribute> lst;
                            for (int x = 0; x < si.DataTypes.Length; x++)
                            {
                                if (!ModuleInfoByInput.TryGetValue(si.DataTypes[x], out lst))
                                {
                                    lst = new List <ModuleInfoAttribute>();
                                    ModuleInfoByInput.Add(si.DataTypes[x], lst);
                                }

                                lst.Add(kv.Key);
                            }
                        }
                    }
                }
            }
            // load Templates
            TemplatesByMenuName.Clear();
            string[] baseFolders;
            if (AssetDatabase.IsValidFolder("Assets/" + CurvyProject.Instance.CustomizationRootPath + CurvyProject.RELPATH_CGTEMPLATES))
            {
                baseFolders = new string[2] {
                    "Assets/" + CurvyEditorUtility.GetPackagePath("CG Templates"),
                    "Assets/" + CurvyProject.Instance.CustomizationRootPath + CurvyProject.RELPATH_CGTEMPLATES
                }
            }
            ;
            else
            {
                baseFolders = new string[1] {
                    "Assets/" + CurvyEditorUtility.GetPackagePath("CG Templates")
                }
            };

            string[] prefabs = AssetDatabase.FindAssets("t:gameobject", baseFolders);

            foreach (var guid in prefabs)
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);
                // Store under a unique menu name
                string name     = AssetDatabase.LoadAssetAtPath(path, typeof(Transform)).name;
                string menuPath = System.IO.Path.GetDirectoryName(path);
                foreach (var s in baseFolders)
                {
                    menuPath = menuPath.TrimStart(s);
                }
                menuPath = menuPath.TrimStart('/');

                string menuName = string.IsNullOrEmpty(menuPath) ? name : menuPath + "/" + name;
                int    i        = 0;
                while (TemplatesByMenuName.ContainsKey((i == 0) ? menuName :menuName + i.ToString()))
                {
                    i++;
                }
                TemplatesByMenuName.Add((i == 0) ? menuName : menuName + i.ToString(), path);
            }
        }
Exemple #13
0
    public static void BuildBundles(string bundlePath, BuildTarget target, BuildAssetBundleOptions assetBundleOptions)
    {
        Debug.Log("Verifying asset registries ..");
        var ok = TestRegistries();

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

        PrepareRegistries();

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

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

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

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

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

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

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

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

            builds.Add(build);

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


            var singleAssetGUIDs = new List <string>();

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

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

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

                path = AssetDatabase.GUIDToAssetPath(singleAssetBundleGUID);

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

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

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


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

            // Set write time so tools can show time since build
            Directory.SetLastWriteTime(bundlePath, DateTime.Now);
        }
    }
        public override void OnEnable()
        {
            base.OnEnable();

            var pageList        = rootVisualElement.Q("page-list");
            var topicsFileGuids = AssetDatabase.FindAssets($"t:{nameof(VisualTreeAsset)}", new string[] { $"{DocumentationRoot}/topics" });
            var topicsFilePaths = topicsFileGuids.Select(AssetDatabase.GUIDToAssetPath).ToArray();
            var uxmlTopics      = topicsFilePaths.Distinct().ToArray();
            var pageFiles       = uxmlTopics
                                  .OrderBy(dir => Path.GetDirectoryName(dir))
                                  .ThenBy(path => Path.GetFileNameWithoutExtension(path))
                                  .ToArray();

            pageList.RegisterCallback <KeyDownEvent>(OnNavigate);
            pageList.Clear();

            var       pages       = new Dictionary <string, PageEntry>();
            PageEntry defaultPage = null;

            foreach (var pagePath in pageFiles)
            {
                var fileName            = Path.GetFileNameWithoutExtension(pagePath);
                var containingDirectory = Path.GetDirectoryName(pagePath);
                var pageNamePath        = Path.Combine(containingDirectory, fileName);

                var fullParentPageName = GetPageName(containingDirectory);
                var fullPageName       = GetPageName(pageNamePath);
                var parentPage         = pages.TryGetValue(fullParentPageName, out var tempPage) ? tempPage : null;

                int pageDepth = 0;
                if (parentPage != null)
                {
                    pageDepth = parentPage.Depth + 1;
                }

                var pageEntry = new PageEntry(fileName, fullPageName, pagePath, pageDepth);
                pageEntry.FoldOut.RegisterCallback <ChangeEvent <bool> >(OnToggle);
                pageEntry.AddManipulator(new Clickable(OnSelect));
                if (fullPageName.Equals("topics-1st_read_me!"))
                {
                    defaultPage = pageEntry;
                }
                if (parentPage != null)
                {
                    var parentIndex = pageList.IndexOf(parentPage);
                    pageEntry.AddToClassList(HiddenClass);
                    pageEntry.AddToClassList(MinimizeClass);
                    pageList.Insert(parentIndex + parentPage.ChildPageCount + 1, pageEntry);
                    parentPage.FoldOut.RemoveFromClassList(HiddenClass);
                    parentPage.ChildPageCount++;
                }
                else
                {
                    pageList.Add(pageEntry);
                }
#if UNITY_2019_1_OR_NEWER
                rootVisualElement.RegisterCallback <CustomStyleResolvedEvent>(OnStyleResolved);
#endif
                pages.Add(fullPageName, pageEntry);
            }
            if (defaultPage != null)
            {
                LoadSelection(defaultPage);
            }
        }
Exemple #15
0
    //[MenuItem("SetAssetFormat/纹理格式/设置XX下的纹理")]
    static void SetAtlasTextureFormat()
    {
        string[] path = new string[2];
        path[0] = @"Assets/ResourcesForAB/Atlas";
        path[1] = @"Assets/ResourcesForAB/UITexture";
        string[] dirRes = AssetDatabase.FindAssets("t:texture2D", path);
        int      i      = 1;

        foreach (string s in dirRes)
        {
            string assetPathName = AssetDatabase.GUIDToAssetPath(s);
            if (EditorUtility.DisplayCancelableProgressBar("设置图片格式", assetPathName, (float)i / (float)dirRes.Length))
            {
                break;
            }
            TextureImporter textureImporter = AssetImporter.GetAtPath(assetPathName) as TextureImporter;
            //textureImporter.textureType = TextureImporterType.Advanced;
            //textureImporter.generateCubemap = TextureImporterGenerateCubemap.None;
            //textureImporter.isReadable = false;
            ////textureImporter.grayscaleToAlpha = false;
            //textureImporter.spriteImportMode = SpriteImportMode.None;
            //textureImporter.mipmapEnabled = false;
            //textureImporter.wrapMode = TextureWrapMode.Clamp;
            //textureImporter.filterMode = FilterMode.Bilinear;
            //textureImporter.anisoLevel = 0;
            //textureImporter.compressionQuality = 100;
            //int maxSize = textureImporter.maxTextureSize;
            //setPlatformTexture("iPhone", maxSize, textureImporter);
            //setPlatformTexture("Android", maxSize, textureImporter);
            //AssetDatabase.ImportAsset(assetPathName);
            //Debug.Log(assetPathName);
            bool changed = false;
            if (textureImporter.textureType != TextureImporterType.Default)
            {
                textureImporter.textureType = TextureImporterType.Default;
                changed = true;
            }
            if (textureImporter.generateCubemap != TextureImporterGenerateCubemap.None)
            {
                textureImporter.generateCubemap = TextureImporterGenerateCubemap.None;
                changed = true;
            }
            if (textureImporter.isReadable != false)
            {
                textureImporter.isReadable = false;
                changed = true;
            }
            if (textureImporter.spriteImportMode != SpriteImportMode.None)
            {
                textureImporter.spriteImportMode = SpriteImportMode.None;
                changed = true;
            }
            if (textureImporter.mipmapEnabled != false)
            {
                textureImporter.mipmapEnabled = false;
                changed = true;
            }
            if (textureImporter.wrapMode != TextureWrapMode.Clamp)
            {
                textureImporter.wrapMode = TextureWrapMode.Clamp;
                changed = true;
            }
            if (textureImporter.filterMode != FilterMode.Bilinear)
            {
                textureImporter.filterMode = FilterMode.Bilinear;
                changed = true;
            }
            if (textureImporter.anisoLevel != 0)
            {
                textureImporter.anisoLevel = 0;
                changed = true;
            }
            if (textureImporter.compressionQuality != 100)
            {
                textureImporter.compressionQuality = 100;
                changed = true;
            }
            int maxSize = textureImporter.maxTextureSize;
            if (setPlatformTexture("iPhone", maxSize, textureImporter))
            {
                changed = true;
            }
            if (setPlatformTexture("Android", maxSize, textureImporter))
            {
                changed = true;
            }
            if (changed)
            {
                AssetDatabase.ImportAsset(assetPathName);
                Debug.Log(assetPathName + "设置成功");
            }
            else
            {
                Debug.Log(assetPathName + "以前已成功设置");
            }
            i++;
        }
        EditorUtility.ClearProgressBar();
    }
        /// <summary>
        /// Get the path to the named asset (just the first found, there should be no multiples). Will return empty if not found.
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        private static string GetPathFromAssetName(string a)
        {
            var id = AssetDatabase.FindAssets(a);

            return((id.Length == 0) ? "" : AssetDatabase.GUIDToAssetPath(id[0]));
        }
Exemple #17
0
#if UNITY_EDITOR
using System.Collections.Generic; 
using UnityEditor; 

/// <summary>
/// Returns all assets of the wanted type
/// </summary>
public static class FindAssetsByType  {

    public static List<T> FindAssetsOfType<T>() where T : UnityEngine.Object
    {
        List<T> assets = new List<T>();
        string[] guids = AssetDatabase.FindAssets(string.Format("t:{0}", typeof(T)));
        for (int i = 0; i < guids.Length; i++)
        {
            string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]);
            T asset = AssetDatabase.LoadAssetAtPath<T>(assetPath);
            if (asset != null)
            {
                assets.Add(asset);
            }
        }

        return assets;
    }
}
#endif

Exemple #18
0
 public static int GetNumberOfInstancesOfScriptableObjectType <T>() where T : ScriptableObject
 {
     return(AssetDatabase.FindAssets("t:" + typeof(T).Name).Length);
 }
Exemple #19
0
    static void DoSeperateAllTexturesRGBandAlphaChannel(BuildTarget buildTarget)
    {
        if (!GetDefaultWhiteTexture())
        {
            return;
        }
        ReloadConfig();

        string[] searchInFolders = { "Assets/UI" };
        string[] guids           = AssetDatabase.FindAssets("t:Material", searchInFolders);

        foreach (string guid in guids)
        {
            string path = AssetDatabase.GUIDToAssetPath(guid);

            Material material = AssetDatabase.LoadMainAssetAtPath(path) as Material;
            if (material == null)
            {
                Debug.LogError("无效材质路径: " + path);
                continue;
            }
            AtlasOrFontConfig config;
            if (IsNormalMaterial(path, buildTarget, out config))
            {
                material.shader = Shader.Find("Unlit/Transparent Colored");
                if (material.HasProperty("_MainTex"))
                {
                    // 设置材质
                    string  mainTexPath = Path.ChangeExtension(path, ".png");
                    Texture mainTex     = AssetDatabase.LoadMainAssetAtPath(mainTexPath) as Texture;
                    if (mainTex != null)
                    {
                        material.SetTexture("_MainTex", mainTex);
                    }
                }
            }
            else
            {
                material.shader = Shader.Find("Unlit/Transparent RGB Alpha");
                if (material.HasProperty("_MainTex") && material.HasProperty("_AlphaTex"))
                {
                    var texturePath = Path.ChangeExtension(path, ".png");
                    if (string.IsNullOrEmpty(texturePath))
                    {
                        throw new Exception("严重错误,文件不存在: " + texturePath);
                    }

                    if (ValidateTexture(texturePath))
                    {
                        string mainTexPath  = string.Empty;
                        string alphaTexPath = string.Empty;
                        // 分离图片
                        SeperateRGBAandAlphaChannel(texturePath, buildTarget, out mainTexPath, out alphaTexPath, config.alphaMip ? 1 : 0);

                        if (!string.IsNullOrEmpty(mainTexPath) && !string.IsNullOrEmpty(alphaTexPath))
                        {
                            // 设置材质
                            Texture mainTex = AssetDatabase.LoadMainAssetAtPath(mainTexPath) as Texture;
                            material.SetTexture("_MainTex", mainTex);
                            Texture alphaTex = AssetDatabase.LoadMainAssetAtPath(alphaTexPath) as Texture;
                            material.SetTexture("_AlphaTex", alphaTex);
                        }
                    }
                    else if (material.GetTexture("_AlphaTex") == null)
                    {
                        string alphaTexPath = path.Substring(0, path.LastIndexOf(".")) + "_Alpha.png";
                        if (File.Exists(alphaTexPath))
                        {
                            Texture alphaTex = AssetDatabase.LoadMainAssetAtPath(alphaTexPath) as Texture;
                            material.SetTexture("_AlphaTex", alphaTex);
                        }
                        else
                        {
                            throw new Exception(string.Format("{0} AlphaTex or rawTex is Null", path));
                        }
                    }
                }
            }
        }

        //Refresh to ensure new generated RBA and Alpha textures shown in Unity as well as the meta file
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
Exemple #20
0
        public override List <AnalyzeResult> RefreshAnalysis(AddressableAssetSettings settings)
        {
            List <AnalyzeResult> results = new List <AnalyzeResult>();

            ClearAnalysis();
            ClearOurData();

            if (!BuildUtility.CheckModifiedScenesAndAskToSave())
            {
                Debug.LogError("Cannot run Analyze with unsaved scenes");
                results.Add(new AnalyzeResult {
                    resultName = ruleName + "Cannot run Analyze with unsaved scenes"
                });
                return(results);
            }

            // Get all folders in Assets/AutoBundles

            HashSet <string> folderNames = new HashSet <string>();
            var folders = AssetDatabase.GetSubFolders("Assets/" + autoBundlesFolderName);

            foreach (var folder in folders)
            {
                folderNames.Add(Path.GetFileName(folder));
            }

            // Get all addressable groups carrying the (Auto) prefix

            HashSet <string> autoGroups = new HashSet <string>();

            foreach (var group in settings.groups)
            {
                if (group.name.StartsWith(autoGroupPrefix))
                {
                    autoGroups.Add(group.name);
                }
            }

            // Collect all groups that must be created or moved

            foreach (var folder in folderNames)
            {
                var autoName = autoGroupPrefix + folder;
                if (!autoGroups.Contains(autoName))
                {
                    groupsToCreate.Add(autoName);
                    results.Add(new AnalyzeResult()
                    {
                        resultName = "Create group \"" + autoName + "\""
                    });
                }
            }

            // Collect all groups that must be removed

            foreach (var groupName in autoGroups)
            {
                var baseName = groupName.Substring(autoGroupPrefix.Length);
                if (!folderNames.Contains(baseName))
                {
                    groupsToRemove.Add(groupName);
                    results.Add(new AnalyzeResult()
                    {
                        resultName = "Remove group \"" + groupName + "\""
                    });
                }
            }

            // Collect all assets that have zero or one references. They will not be bundled, because
            // Addressables will automatically bring them in. This reduces the number of individual bundles.

            Dictionary <string, int> refCounts = new Dictionary <string, int>();
            var guids = AssetDatabase.FindAssets(assetFilter, new [] { "Assets" });

            foreach (var guid in guids)
            {
                string path = AssetDatabase.GUIDToAssetPath(guid);

                var dependencies = AssetDatabase.GetDependencies(path);
                foreach (var asset in dependencies)
                {
                    if (asset == path)
                    {
                        // Ignore self
                        continue;
                    }
                    if (refCounts.ContainsKey(asset))
                    {
                        refCounts[asset]++;
                    }
                    else
                    {
                        refCounts[asset] = 1;
                    }
                }
            }

            // Select which items to never bundle. This includes items that have no references or only one references,
            // as well as unwanted file extensions.

            HashSet <string> neverBundle = new HashSet <string>();

            foreach (KeyValuePair <string, int> asset in refCounts)
            {
                if (asset.Value == 0 && neverBundleNoReferences || asset.Value == 1)
                {
                    neverBundle.Add(asset.Key);
                    break;
                }

                bool ignore = false;
                foreach (var ext in ignoreExtensions)
                {
                    if (asset.Key.ToLower().EndsWith(ext))
                    {
                        ignore = true;
                        break;
                    }
                }
                if (ignore)
                {
                    neverBundle.Add(asset.Key);
                }
            }

            // Collect all assets to create as addressables

            string preamble = "Assets/" + autoBundlesFolderName + "/";

            foreach (var folder in folderNames)
            {
                var assetGuids = AssetDatabase.FindAssets(assetFilter, new [] { "Assets/" + autoBundlesFolderName + "/" + folder });

                // Schedule creation/moving of assets that exist

                foreach (var guid in assetGuids)
                {
                    var addrPath = AssetDatabase.GUIDToAssetPath(guid);

                    // Skip assets we're never bundling

                    if (neverBundle.Contains(addrPath))
                    {
                        continue;
                    }

                    // Remove the Assets/AutoBundles/ part of assets paths.

                    if (addrPath.StartsWith(preamble))
                    {
                        addrPath = addrPath.Substring(preamble.Length);
                    }

                    // Create asset creation/moving action.

                    string autoGroup = autoGroupPrefix + folder;

                    assetActions.Add(new AssetAction()
                    {
                        create          = true,
                        inGroup         = autoGroup,
                        assetGuid       = guid,
                        addressablePath = addrPath
                    });

                    AddressableAssetEntry entry = settings.FindAssetEntry(guid);
                    if (entry == null)
                    {
                        results.Add(new AnalyzeResult()
                        {
                            resultName = "Add:" + addrPath
                        });
                    }
                    else
                    {
                        results.Add(new AnalyzeResult()
                        {
                            resultName = "Keep or move:" + addrPath
                        });
                    }
                }

                // Schedule removal of assets that exist as addressables but don't exist anywhere under the AutoBundles tree

                string autoName = autoGroupPrefix + folder;
                var    group    = settings.FindGroup(autoName);

                if (group != null)
                {
                    List <AddressableAssetEntry> result = new List <AddressableAssetEntry>();
                    group.GatherAllAssets(result, true, true, true);

                    foreach (var entry in result)
                    {
                        if (entry.IsSubAsset)
                        {
                            continue;
                        }
                        if (entry.guid == "")
                        {
                            Debug.Log("Entry has no guid! " + entry.address);
                        }

                        string assetPath = AssetDatabase.GUIDToAssetPath(entry.guid);


                        if (!assetPath.StartsWith("Assets/" + autoBundlesFolderName + "/"))
                        {
                            assetActions.Add(new AssetAction()
                            {
                                create          = false,
                                inGroup         = autoName,
                                assetGuid       = entry.guid,
                                addressablePath = entry.address,
                            });

                            // Print removal message without preamble

                            results.Add(new AnalyzeResult()
                            {
                                resultName = "Remove:" + entry.address
                            });
                        }
                    }
                }
            }

            return(results);
        }
Exemple #21
0
        /// <summary>
        /// Check for Updates with GitHub
        /// </summary>
        static void CheckForUpdate()
        {
            var fileContent = string.Empty;

            EditorUtility.DisplayProgressBar("VSCode", "Checking for updates ...", 0.5f);

            // Because were not a runtime framework, lets just use the simplest way of doing this
            try
            {
                using (var webClient = new System.Net.WebClient())
                {
                    fileContent = webClient.DownloadString("https://raw.githubusercontent.com/dotBunny/VSCode/master/Plugins/Editor/VSCode.cs");
                }
            }
            catch (Exception e)
            {
                if (Debug)
                {
                    UnityEngine.Debug.Log("[VSCode] " + e.Message);
                }

                // Don't go any further if there is an error
                return;
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }

            // Set the last update time
            LastUpdate = DateTime.Now;

            // Fix for oddity in downlo
            if (fileContent.Substring(0, 2) != "/*")
            {
                int startPosition = fileContent.IndexOf("/*", StringComparison.CurrentCultureIgnoreCase);

                // Jump over junk characters
                fileContent = fileContent.Substring(startPosition);
            }

            string[] fileExploded = fileContent.Split('\n');
            if (fileExploded.Length > 7)
            {
                float github = Version;
                if (float.TryParse(fileExploded[6].Replace("*", "").Trim(), out github))
                {
                    GitHubVersion = github;
                }


                if (github > Version)
                {
                    var GUIDs = AssetDatabase.FindAssets("t:Script VSCode");
                    var path  = Application.dataPath.Substring(0, Application.dataPath.Length - "/Assets".Length) + System.IO.Path.DirectorySeparatorChar +
                                AssetDatabase.GUIDToAssetPath(GUIDs[0]).Replace('/', System.IO.Path.DirectorySeparatorChar);

                    if (EditorUtility.DisplayDialog("VSCode Update", "A newer version of the VSCode plugin is available, would you like to update your version?", "Yes", "No"))
                    {
                        // Always make sure the file is writable
                        System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);
                        fileInfo.IsReadOnly = false;

                        // Write update file
                        File.WriteAllText(path, fileContent);

                        // Force update on text file
                        AssetDatabase.ImportAsset(AssetDatabase.GUIDToAssetPath(GUIDs[0]), ImportAssetOptions.ForceUpdate);
                    }
                }
            }
        }
 public static string[] FindAsset(Type type)
 {
     return(AssetDatabase.FindAssets("t:" + type.Name));
 }
Exemple #23
0
    void Start()
    {
        MonoBehaviour[] scripts = MonoBehaviour.FindObjectsOfType <MonoBehaviour>();
        foreach (MonoBehaviour s in scripts)
        {
            IEnumerable <FieldInfo> fields = s.GetType().GetFields();
            foreach (FieldInfo f in fields)
            {
                if (f.FieldType.Equals(typeof(KMBombInfo)))
                {
                    KMBombInfo component = (KMBombInfo)f.GetValue(s);
                    if (component.OnBombExploded != null)
                    {
                        fakeInfo.Detonate += new FakeBombInfo.OnDetonate(component.OnBombExploded);
                    }
                    if (component.OnBombSolved != null)
                    {
                        fakeInfo.HandleSolved += new FakeBombInfo.OnSolved(component.OnBombSolved);
                    }
                    continue;
                }
            }
        }

        currentSelectable = GetComponent <TestSelectable>();

        KMBombModule[]  modules      = FindObjectsOfType <KMBombModule>();
        KMNeedyModule[] needyModules = FindObjectsOfType <KMNeedyModule>();
        fakeInfo.needyModules      = needyModules.ToList();
        currentSelectable.Children = new TestSelectable[modules.Length + needyModules.Length];
        for (int i = 0; i < modules.Length; i++)
        {
            KMBombModule mod = modules[i];

            currentSelectable.Children[i] = modules[i].GetComponent <TestSelectable>();
            modules[i].GetComponent <TestSelectable>().Parent = currentSelectable;

            fakeInfo.modules.Add(new KeyValuePair <KMBombModule, bool>(modules[i], false));
            modules[i].OnPass = delegate() {
                Debug.Log("Module Passed");
                fakeInfo.modules.Remove(fakeInfo.modules.First(t => t.Key.Equals(mod)));
                fakeInfo.modules.Add(new KeyValuePair <KMBombModule, bool>(mod, true));
                bool allSolved = true;
                foreach (KeyValuePair <KMBombModule, bool> m in fakeInfo.modules)
                {
                    if (!m.Value)
                    {
                        allSolved = false;
                        break;
                    }
                }
                if (allSolved)
                {
                    fakeInfo.Solved();
                }
                return(false);
            };
            modules[i].OnStrike = delegate() {
                Debug.Log("Strike");
                fakeInfo.HandleStrike();
                return(false);
            };
        }

        for (int i = 0; i < needyModules.Length; i++)
        {
            currentSelectable.Children[modules.Length + i]         = needyModules[i].GetComponent <TestSelectable>();
            needyModules[i].GetComponent <TestSelectable>().Parent = currentSelectable;

            needyModules[i].OnPass = delegate()
            {
                Debug.Log("Module Passed");
                return(false);
            };
            needyModules[i].OnStrike = delegate()
            {
                Debug.Log("Strike");
                fakeInfo.HandleStrike();
                return(false);
            };
        }

        currentSelectable.ActivateChildSelectableAreas();


        //Load all the audio clips in the asset database
        audioClips = new List <AudioClip>();
        string[] audioClipAssetGUIDs = AssetDatabase.FindAssets("t:AudioClip");

        foreach (var guid in audioClipAssetGUIDs)
        {
            AudioClip clip = AssetDatabase.LoadAssetAtPath <AudioClip>(AssetDatabase.GUIDToAssetPath(guid));

            if (clip != null)
            {
                audioClips.Add(clip);
            }
        }

        audioSource = gameObject.AddComponent <AudioSource>();
        KMAudio[] kmAudios = FindObjectsOfType <KMAudio>();
        foreach (KMAudio kmAudio in kmAudios)
        {
            kmAudio.HandlePlaySoundAtTransform += PlaySoundHandler;
        }
    }
Exemple #24
0
    private static SelectionSearchResponse RequestSearch(Component[] allComps, SelectionSearchRequest req)
    {
        var resp = new SelectionSearchResponse
        {
            request        = req,
            referencePairs = new List <ReferencePair>()
        };

        var goType         = typeof(GameObject);
        var spriteType     = typeof(Sprite);
        var textureType    = typeof(Texture2D);
        var targetObjects  = req.targetObjects;
        var selectedObject = req.selectedObject;

        //All components in scene
        foreach (var sComp in allComps)
        {
            var type   = sComp.GetType();
            var fields = type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            //All fields in that component
            foreach (var field in fields)
            {
                {
                    var fieldType    = field.FieldType;
                    var isFieldArray = fieldType.IsArray;


                    foreach (var targetObject in targetObjects)
                    {
                        System.Type targetType = targetObject.GetType();
                        if (isFieldArray && IsAssignableFrom(fieldType, targetType))
                        {
                            var array = field.GetValue(sComp) as IList;
                            if (array != null)
                            {
                                var index = 0;
                                foreach (Object fieldValue in array)
                                {
                                    if (AreEqual(fieldValue, targetObject))
                                    {
                                        var pair = new ReferencePair()
                                        {
                                            referenceOwnerObject = sComp,
                                            targetObject         = fieldValue,
                                            referenceFiledName   = field.Name,
                                            referenceArrayIndex  = index
                                        };
                                        resp.referencePairs.Add(pair);
                                    }
                                    index++;
                                }
                            }
                        }

                        if (IsAssignableFrom(fieldType, targetType))
                        {
                            var fieldValue = field.GetValue(sComp) as Object;
                            if (AreEqual(fieldValue, targetObject))
                            {
                                var pair = new ReferencePair()
                                {
                                    referenceOwnerObject = sComp,
                                    targetObject         = fieldValue,
                                    referenceFiledName   = field.Name,
                                };
                                resp.referencePairs.Add(pair);
                            }
                        }
                    }
                }
            }
        }

        string[] searchInFolders = new string[] { "Assets" };
        string   dataPath        = Application.dataPath.Replace("Assets", "");

        foreach (var item in resp.referencePairs)
        {
            if (item.referenceOwnerObject is Component)
            {
                var guids = AssetDatabase.FindAssets("t:Script " + item.referenceOwnerObject.GetType().Name, searchInFolders);
                if (guids.Length > 0)
                {
                    string assetPath = AssetDatabase.GUIDToAssetPath(guids[0]);
                    item.referenceOwnerScriptPath = assetPath;
                    string path = dataPath + assetPath;
                    item.scriptObject = AssetDatabase.LoadAssetAtPath <TextAsset>(assetPath);
                    if (item.scriptObject != null)
                    {
                        using (StreamReader sr = new StreamReader(path))
                        {
                            int linecount = 1;
                            while (!sr.EndOfStream)
                            {
                                var line = sr.ReadLine();
                                if (line.Contains(item.referenceFiledName))
                                {
                                    item.referenceFiledLineNumber = linecount;
                                    break;
                                }
                                linecount++;
                            }
                        }
                    }
                }
            }
        }

        return(resp);
    }
Exemple #25
0
        public static void Init()
        {
            if (!Initialized)
            {
                m_availableTemplates = new Dictionary <string, TemplateData>();
                m_sortedTemplates    = new List <TemplateData>();

                // Post-Process
                {
                    TemplateData postProcess = new TemplateData("Post Process", "c71b220b631b6344493ea3cf87110c93");
                    if (postProcess.IsValid)
                    {
                        AddTemplate(postProcess);
                    }
                }

                // Default Unlit
                {
                    TemplateData defaultUnlit = new TemplateData("Default Unlit", "6e114a916ca3e4b4bb51972669d463bf");
                    if (defaultUnlit.IsValid)
                    {
                        AddTemplate(defaultUnlit);
                    }
                }

                // UI
                {
                    TemplateData defaultUI = new TemplateData("Default UI", "5056123faa0c79b47ab6ad7e8bf059a4");
                    if (defaultUI.IsValid)
                    {
                        AddTemplate(defaultUI);
                    }
                }

                // Sprites
                {
                    TemplateData defaultSprites = new TemplateData("Default Sprites", "0f8ba0101102bb14ebf021ddadce9b49");
                    if (defaultSprites.IsValid)
                    {
                        AddTemplate(defaultSprites);
                    }
                }

                // Particles
                {
                    TemplateData particlesAlphaBlended = new TemplateData("Particles Alpha Blended", "0b6a9f8b4f707c74ca64c0be8e590de0");
                    if (particlesAlphaBlended.IsValid)
                    {
                        AddTemplate(particlesAlphaBlended);
                    }
                }

                // Particles Cutout
                //{
                //	TemplateData particlesCutout = new TemplateData( "Particles Cutout", "9dc0487e4f202ba49bbef443f0ddf5ca" );
                //	if( particlesCutout.IsValid )
                //		AddTemplate( particlesCutout );
                //}


                // Search for other possible templates on the project
                string[] allShaders = AssetDatabase.FindAssets("t:shader");
                for (int i = 0; i < allShaders.Length; i++)
                {
                    if (!m_availableTemplates.ContainsKey(allShaders[i]))
                    {
                        CheckAndLoadTemplate(allShaders[i]);
                    }
                }

                // TODO: Sort list alphabeticaly
                AvailableTemplateNames    = new string[m_sortedTemplates.Count + 1];
                AvailableTemplateNames[0] = "Custom";
                for (int i = 0; i < m_sortedTemplates.Count; i++)
                {
                    m_sortedTemplates[i].OrderId  = i;
                    AvailableTemplateNames[i + 1] = m_sortedTemplates[i].Name;
                }
                Initialized = true;
            }
        }
Exemple #26
0
        private static void ImportAsset(string importAssetPath)
        {
            var path = importAssetPath.Remove(importAssetPath.Length - Path.GetExtension(importAssetPath).Length);
            var name = Path.GetFileNameWithoutExtension(path);

            if (!name.StartsWith(checkNameStartWith))
            {
                return;
            }

            #region VersionCheck
            try
            {
                Func <string, int> ToVersion = (t) =>
                {
                    return(Convert.ToInt32(Path.GetExtension(t).Remove(0, 1).Replace('_', '0')));
                };

                List <int> versions = new List <int>();
                {
                    var fullPath          = Application.dataPath + importAssetPath.Remove(0, "Assets".Length);
                    var directoryPath     = Path.GetDirectoryName(fullPath);
                    var dllNameWithoutExt = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(importAssetPath));
                    foreach (var p in Directory.GetFiles(directoryPath, "*.asmdefChanger"))
                    {
                        var subDllNameWithoutExt = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(p));
                        if (dllNameWithoutExt != subDllNameWithoutExt)
                        {
                            continue;
                        }

                        var subPath    = p.Remove(p.Length - Path.GetExtension(p).Length);
                        var subVersion = ToVersion(subPath);
                        versions.Add(subVersion);
                    }
                    versions.Sort();
                }

                int targetVersion = -1;
                {
                    var editorVersion = Convert.ToInt32(Path.GetFileNameWithoutExtension(Application.unityVersion).Replace('.', '0'));
                    foreach (var ver in versions)
                    {
                        if (ver <= editorVersion)
                        {
                            targetVersion = ver;
                        }
                    }
                }
                if (targetVersion < 0)
                {
                    return;
                }

                var currentVersion = ToVersion(path);
                if (currentVersion != targetVersion)
                {
                    return;
                }
            }
            catch
            {
                return;
            }
            #endregion

            #region Change
            var originalAssetPath = importAssetPath;
            EditorApplication.delayCall += () =>
            {
                var nameExt = name + ".asmdef";
                foreach (var guid in AssetDatabase.FindAssets(name))
                {
                    var assetPath = AssetDatabase.GUIDToAssetPath(guid);
                    if (Path.GetFileName(assetPath) != nameExt)
                    {
                        continue;
                    }

                    var originalFullPath = Application.dataPath + originalAssetPath.Remove(0, "Assets".Length);
                    var fullPath         = Application.dataPath + assetPath.Remove(0, "Assets".Length);
                    var originalFileInfo = new FileInfo(originalFullPath);
                    var fileInfo         = new FileInfo(fullPath);
                    if (originalFileInfo.Length != fileInfo.Length)
                    {
                        FileUtil.DeleteFileOrDirectory(assetPath);
                        FileUtil.CopyFileOrDirectory(originalAssetPath, assetPath);

                        var importer = AssetImporter.GetAtPath(assetPath);
                        if (importer != null)
                        {
                            importer.SaveAndReimport();
                        }
                        AssetDatabase.Refresh();
                    }
                    break;
                }
            };
            #endregion
        }
Exemple #27
0
        public static void Build()
        {
            DataEditor.AllXmlToBinary();
            m_ConfigFil.Clear();
            m_AllFileAB.Clear();
            m_AllFileDir.Clear();
            m_AllPrefabDir.Clear();
            ABConfig abConfig = AssetDatabase.LoadAssetAtPath <ABConfig>(ABCONFIGPATH);

            foreach (ABConfig.FileDirABName fileDir in abConfig.m_AllFileDirAB)
            {
                if (m_AllFileDir.ContainsKey(fileDir.ABName))
                {
                    Debug.LogError("AB包配置名字重复,请检查!");
                }
                else
                {
                    m_AllFileDir.Add(fileDir.ABName, fileDir.Path);
                    m_AllFileAB.Add(fileDir.Path);
                    m_ConfigFil.Add(fileDir.Path);
                }
            }

            string[] allStr = AssetDatabase.FindAssets("t:Prefab", abConfig.m_AllPrefabPath.ToArray());
            for (int i = 0; i < allStr.Length; i++)
            {
                string path = AssetDatabase.GUIDToAssetPath(allStr[i]);
                EditorUtility.DisplayProgressBar("查找Prefab", "Prefab:" + path, i * 1.0f / allStr.Length);
                m_ConfigFil.Add(path);
                if (!ContainAllFileAB(path))
                {
                    GameObject    obj           = AssetDatabase.LoadAssetAtPath <GameObject>(path);
                    string[]      allDepend     = AssetDatabase.GetDependencies(path);
                    List <string> allDependPath = new List <string>();
                    for (int j = 0; j < allDepend.Length; j++)
                    {
                        if (!ContainAllFileAB(allDepend[j]) && !allDepend[j].EndsWith(".cs"))
                        {
                            m_AllFileAB.Add(allDepend[j]);
                            allDependPath.Add(allDepend[j]);
                        }
                    }
                    if (m_AllPrefabDir.ContainsKey(obj.name))
                    {
                        Debug.LogError("存在相同名字的Prefab!名字:" + obj.name);
                    }
                    else
                    {
                        m_AllPrefabDir.Add(obj.name, allDependPath);
                    }
                }
            }

            foreach (string name in m_AllFileDir.Keys)
            {
                SetABName(name, m_AllFileDir[name]);
            }

            foreach (string name in m_AllPrefabDir.Keys)
            {
                SetABName(name, m_AllPrefabDir[name]);
            }

            BuildAssetBundle();

            string[] oldABNames = AssetDatabase.GetAllAssetBundleNames();
            for (int i = 0; i < oldABNames.Length; i++)
            {
                AssetDatabase.RemoveAssetBundleName(oldABNames[i], true);
                EditorUtility.DisplayProgressBar("清除AB包名", "名字:" + oldABNames[i], i * 1.0f / oldABNames.Length);
            }

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            EditorUtility.ClearProgressBar();
        }
Exemple #28
0
    //[MenuItem("SetAssetFormat/纹理格式/设置下的纹理")]
    static void SetChrTextureFormat()
    {
        string[] path = new string[1];
        path[0] = @"Assets/ResourcesForAB/Model/Monster";
        string[] dirRes = AssetDatabase.FindAssets("t:texture2D", path);
        int      i      = 1;

        foreach (string s in dirRes)
        {
            string assetPathName = AssetDatabase.GUIDToAssetPath(s);
            if (EditorUtility.DisplayCancelableProgressBar("设置图片格式", assetPathName, (float)i / (float)dirRes.Length))
            {
                break;
            }
            TextureImporter textureImporter = AssetImporter.GetAtPath(assetPathName) as TextureImporter;
            //int maxSize = 512;
            //if (assetPathName.IndexOf("boss") == -1) maxSize = 128;
            //textureImporter.SetPlatformTextureSettings("iPhone", maxSize, TextureImporterFormat.PVRTC_RGB4, 100);
            //textureImporter.SetPlatformTextureSettings("Android", maxSize, TextureImporterFormat.ETC_RGB4, 100);

            bool changed = false;
            if (textureImporter.textureType != TextureImporterType.Default)
            {
                textureImporter.textureType = TextureImporterType.Default;
                changed = true;
            }
            if (textureImporter.generateCubemap != TextureImporterGenerateCubemap.None)
            {
                textureImporter.generateCubemap = TextureImporterGenerateCubemap.None;
                changed = true;
            }
            if (textureImporter.isReadable != false)
            {
                textureImporter.isReadable = false;
                changed = true;
            }
            if (textureImporter.spriteImportMode != SpriteImportMode.None)
            {
                textureImporter.spriteImportMode = SpriteImportMode.None;
                changed = true;
            }
            if (textureImporter.mipmapEnabled != true)
            {
                textureImporter.mipmapEnabled = true;
                changed = true;
            }
            if (textureImporter.wrapMode != TextureWrapMode.Repeat)
            {
                textureImporter.wrapMode = TextureWrapMode.Repeat;
                changed = true;
            }
            if (textureImporter.filterMode != FilterMode.Trilinear)
            {
                textureImporter.filterMode = FilterMode.Trilinear;
                changed = true;
            }
            if (textureImporter.anisoLevel != 4)
            {
                textureImporter.anisoLevel = 4;
                changed = true;
            }
            if (textureImporter.compressionQuality != 100)
            {
                textureImporter.compressionQuality = 100;
                changed = true;
            }
            int maxSize = textureImporter.maxTextureSize;
            if (setPlatformTexture("iPhone", maxSize, textureImporter))
            {
                changed = true;
            }
            if (setPlatformTexture("Android", maxSize, textureImporter))
            {
                changed = true;
            }
            if (changed)
            {
                AssetDatabase.ImportAsset(assetPathName);
                Debug.Log(assetPathName + "设置成功");
            }
            else
            {
                Debug.Log(assetPathName + "以前已成功设置");
            }
            i++;
        }
        EditorUtility.ClearProgressBar();
    }
Exemple #29
0
    void OnGUI()
    {
        BtnStyle           = new GUIStyle(GUI.skin.button);
        BtnStyle.fontSize  = 16;
        BtnStyle.alignment = TextAnchor.MiddleLeft;

        LableStyle           = new GUIStyle(GUI.skin.label);
        LableStyle.fontSize  = 16;
        LableStyle.alignment = TextAnchor.MiddleLeft;

        BoxStyle = new GUIStyle(GUI.skin.box);

        assetBundleNames = AssetDatabase.GetAllAssetBundleNames();


        if (assetBundleNames.Length == 0)
        {
            EditorGUILayout.HelpBox("No AssetBundle Data", MessageType.Warning);
            return;
        }

        tabIndex = UtilityEditor.Tabs(Types, tabIndex);
        GUILayout.Space(10);

        string[] assetName = null;

        switch (tabIndex)
        {
        case 0:
            EditorGUILayout.LabelField("Select AssetBundle Names", EditorStyles.boldLabel);

            index = EditorGUILayout.Popup(index, assetBundleNames);
            GUILayout.Space(10f);

            assetName = AssetDatabase.FindAssets("b:" + assetBundleNames[index]);

            EditorGUILayout.BeginVertical();
            this.scrollPos = EditorGUILayout.BeginScrollView(this.scrollPos, false, false);
            EditorGUILayout.Space();


            foreach (string item in assetName)
            {
                string   path  = AssetDatabase.GUIDToAssetPath(item);
                string[] level = path.Split('/');

                if (GUILayout.Button(GetLevelString(level.Length - 1) + path, BtnStyle))
                {
                    EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath <Object>(path));
                }
            }


            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndVertical();

            GUILayout.Space(25.0f);
            break;


        case 1:
            EditorGUILayout.LabelField("AssetBundle", EditorStyles.boldLabel);

            EditorGUILayout.BeginVertical();
            this.scrollPos = EditorGUILayout.BeginScrollView(this.scrollPos, false, false);

            int count = 1;
            foreach (string name in assetBundleNames)
            {
                assetName = AssetDatabase.FindAssets("b:" + name);

                EditorGUILayout.BeginVertical(BoxStyle);
                GUILayout.Label(count.ToString("000") + ".  " + name + ":", LableStyle);
                foreach (string item in assetName)
                {
                    string   path  = AssetDatabase.GUIDToAssetPath(item);
                    string[] level = path.Split('/');

                    if (GUILayout.Button(GetLevelString(level.Length - 1) + path, BtnStyle))
                    {
                        EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath <Object>(path));
                    }
                }
                EditorGUILayout.EndVertical();

                count++;
                GUILayout.Space(25.0f);
            }

            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndVertical();

            GUILayout.Space(25.0f);
            break;
        }
    }
Exemple #30
0
 private void OnEnable()
 {
     list = new ReorderableList(serializedObject,
                                serializedObject.FindProperty("Waves"),
                                true, true, true, true);
     list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => {
         var element = list.serializedProperty.GetArrayElementAtIndex(index);
         rect.y += 2;
         EditorGUI.PropertyField(new Rect(rect.x, rect.y, 60, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("Type"), GUIContent.none);
         EditorGUI.PropertyField(new Rect(rect.x + 60, rect.y, rect.width - 60 - 30, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("Prefab"), GUIContent.none);
         EditorGUI.PropertyField(new Rect(rect.x + rect.width - 30, rect.y, 30, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("Count"), GUIContent.none);
     };
     list.drawHeaderCallback = (Rect rect) => {
         EditorGUI.LabelField(rect, "Monster Waves");
     };
     list.onSelectCallback = (ReorderableList l) => {
         var prefab = l.serializedProperty.GetArrayElementAtIndex(l.index).FindPropertyRelative("Prefab").objectReferenceValue as GameObject;
         if (prefab)
         {
             EditorGUIUtility.PingObject(prefab.gameObject);
         }
     };
     list.onCanRemoveCallback = (ReorderableList l) => {
         return(l.count > 1);
     };
     list.onRemoveCallback = (ReorderableList l) => {
         if (EditorUtility.DisplayDialog("Warning!", "Are you sure you want to delete the wave?", "Yes", "No"))
         {
             ReorderableList.defaultBehaviours.DoRemoveButton(l);
         }
     };
     list.onAddCallback = (ReorderableList l) => {
         var index = l.serializedProperty.arraySize;
         l.serializedProperty.arraySize++;
         l.index = index;
         var element = l.serializedProperty.GetArrayElementAtIndex(index);
         element.FindPropertyRelative("Type").enumValueIndex         = 0;
         element.FindPropertyRelative("Count").intValue              = 20;
         element.FindPropertyRelative("Prefab").objectReferenceValue = AssetDatabase.LoadAssetAtPath("Assets/Resources/Prefabs/Mobs/Turtle Boss.prefab", typeof(GameObject)) as GameObject;
     };
     list.onAddDropdownCallback = (Rect buttonRect, ReorderableList l) => {
         var menu  = new GenericMenu();
         var guids = AssetDatabase.FindAssets("", new[] { "Assets/Resources/Prefabs/Mobs" });
         foreach (var guid in guids)
         {
             var path = AssetDatabase.GUIDToAssetPath(guid);
             menu.AddItem(new GUIContent("Mobs/" + Path.GetFileNameWithoutExtension(path)), false, clickHandler, new WaveCreationParams()
             {
                 Type = MobWave.WaveType.Mobs, Path = path
             });
         }
         guids = AssetDatabase.FindAssets("", new[] { "Assets/Resources/Prefabs/Boss" });
         foreach (var guid in guids)
         {
             var path = AssetDatabase.GUIDToAssetPath(guid);
             menu.AddItem(new GUIContent("Boss/" + Path.GetFileNameWithoutExtension(path)), false, clickHandler, new WaveCreationParams()
             {
                 Type = MobWave.WaveType.Boss, Path = path
             });
         }
         menu.ShowAsContext();
     };
 }