private void OnSceneOpened(Scene scene, OpenSceneMode mode)
        {
            if (!BuildPipeline.isBuildingPlayer)
            {
                return;
            }
            if (this != activeInstance)
            {
                return;
            }

            Debug.Assert(!BuildInfoSettings.Instance.useLegacyCallbacks);
            preexistingPrefabInstances.Clear();

            // collect all scene objects
            var allGameObjects = EditorUtility.CollectDeepHierarchy(scene.GetRootGameObjects())
                                 .OfType <GameObject>()
                                 .Where(x => PrefabUtility.GetPrefabInstanceStatus(x) == PrefabInstanceStatus.Connected);

            // store all the prefabs please
            foreach (var gameObject in allGameObjects)
            {
                var prefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(gameObject);
                if (string.IsNullOrEmpty(prefabPath))
                {
                    Log.Debug("Prefab not found for {0}, how come?", gameObject);
                }
                else
                {
                    preexistingPrefabInstances.Add(gameObject.GetInstanceID(), prefabPath);
                }
            }
        }
        public Object   EditorResolveSlow(bool bLoadScene)
        {
            var scene = this.scene.scene;

            if (!scene.IsValid())
            {
                return(null);
            }

            if (!scene.isLoaded)
            {
                if (!bLoadScene)
                {
                    return(null);
                }

                EditorSceneManager.LoadScene(scene.path);
            }

            AmsDebug.LogError(null, "Performing EditorResolveSlow but it was never tested");

            // Find the object (this is potentially very slow).
            Object[] allObjs = EditorUtility.CollectDeepHierarchy(scene.GetRootGameObjects());
            foreach (var obj in allObjs)
            {
                if (editorLocalId == Unsupported.GetLocalIdentifierInFile(obj.GetInstanceID()))
                {
                    return(obj);
                }
            }

            return(null);
        }
Пример #3
0
        private static void CollectDetailsForPrefab(List <AssetProperty> props, GameObject prefab)
        {
            var hierarchy = EditorUtility.CollectDeepHierarchy(new[] { prefab });

            props.Add(AssetProperty.Create("GameObjects", hierarchy.Count(x => x is GameObject)));
            props.Add(AssetProperty.Create("Components", hierarchy.Count(x => x is Component)));
        }
Пример #4
0
    public static bool DoPatch(Transform xffect)
    {
        bool needToReimport = false;

        Object[] deps = EditorUtility.CollectDeepHierarchy(new Object[] { xffect.gameObject as Object });

        foreach (Object obj in deps)
        {
            if (obj == null || obj.GetType() != typeof(GameObject))
            {
                continue;
            }
            GameObject  go  = obj as GameObject;
            EffectLayer efl = go.GetComponent <EffectLayer>();
            if (efl != null)
            {
                DoPatch(efl);
                needToReimport = true;
            }

            XftEventComponent xevent = go.GetComponent <XftEventComponent>();
            if (xevent != null)
            {
                DoPatch(xevent);
                needToReimport = true;
            }
        }

        return(needToReimport);
    }
Пример #5
0
        static void init()
        {
            pb_Editor_Utility.ShowNotification("Set Pivot", "Center pivot around current selection.");

            pb_Object[] pbObjects = GetSelection();
            if (pbObjects.Length > 0)
            {
                        #if !UNITY_4_3
                Undo.RegisterUndo(EditorUtility.CollectDeepHierarchy(Selection.transforms as Object[]), "set object(s) pivot point.");
                        #else
                Undo.RecordObjects(EditorUtility.CollectDeepHierarchy(Selection.transforms as Object[]), "set object(s) pivot point.");
                        #endif

                foreach (pb_Object pbo in pbObjects)
                {
                    if (pbo.selected_triangles.Length > 0)
                    {
                        SetPivot(pbo, pbo.selected_triangles, false);
                    }
                    else
                    {
                        SetPivot(pbo, pbo.uniqueIndices, true);
                    }
                }
            }
        }
Пример #6
0
 private static void OnEnable()
 {
     try
     {
         var deepSelection = EditorUtility.CollectDeepHierarchy(Selection.gameObjects);
         int compCount     = 0;
         int goCount       = 0;
         foreach (var o in deepSelection)
         {
             if (o is GameObject go)
             {
                 int count = GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(go);
                 if (count > 0)
                 {
                     Undo.RegisterCompleteObjectUndo(go, "Remove missing scripts");
                     GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
                     compCount += count;
                     goCount++;
                 }
             }
         }
         Debug.Log($"Found {compCount} missing Scripts from {goCount} Gameobjects - All of them got Deleted.");
     }
     catch (Exception ex)
     {
         EditorUtility.DisplayDialog("theblackarmsSDX", "delete_missing-Scripts.InGameObject: " + ex.Message, "Okay");
     }
 }
Пример #7
0
    public static void BridgeEdges()
    {
                #if !UNITY_4_3
        Undo.RegisterUndo(EditorUtility.CollectDeepHierarchy(Selection.transforms as Object[]), "Bridge selected edges.");
                #else
        Undo.RecordObjects(EditorUtility.CollectDeepHierarchy(Selection.transforms as Object[]), "Bridge selected edges.");
                #endif

        bool success = false;
        bool limitToPerimeterEdges = pb_Preferences_Internal.GetBool(pb_Constant.pbPerimeterEdgeBridgeOnly);
        foreach (pb_Object pb in pbUtil.GetComponents <pb_Object>(Selection.transforms))
        {
            if (pb.selected_edges.Length == 2)
            {
                if (pb.Bridge(pb.selected_edges[0], pb.selected_edges[1], limitToPerimeterEdges))
                {
                    success = true;
                }
            }
        }
        if (success)
        {
            pb_Editor_Utility.ShowNotification("Bridge Edges", "");
        }
    }
Пример #8
0
    // ------------------------------------------------------------------
    // Desc:
    // ------------------------------------------------------------------

    static void GetSpritesFromPrefabs(string _path, ref List <exSpriteBase> _sprites)
    {
        // Process the list of files found in the directory.
        string [] files = Directory.GetFiles(_path, "*.prefab");
        foreach (string fileName in files)
        {
            Object prefab = (Object)AssetDatabase.LoadAssetAtPath(fileName, typeof(Object));
            if (prefab)
            {
                Object [] objs = EditorUtility.CollectDeepHierarchy(new Object [] { prefab });
                foreach (Object o in objs)
                {
                    GameObject go = o as GameObject;
                    if (go != null)
                    {
                        exSpriteBase sp = go.GetComponent <exSpriteBase>();
                        if (sp != null)
                        {
                            _sprites.Add(sp);
                        }
                    }
                }
            }
        }

        // Recurse into subdirectories of this directory.
        string [] dirs = Directory.GetDirectories(_path);
        foreach (string dirName in dirs)
        {
            GetSpritesFromPrefabs(dirName, ref _sprites);
        }
    }
Пример #9
0
    private void DrawDeepHierarchy()
    {
        GUILayout.Label("DeepHierarchy:");
        var dependencies = EditorUtility.CollectDeepHierarchy(new[] { Selection.activeObject });

        foreach (var obj in dependencies)
        {
            GUILayout.Label(AssetDatabase.GetAssetPath(obj) + "  :  " + obj);
        }
    }
    public override void OnInspectorGUI()
    {
        var sizer = (tk2dUILayoutContainerSizer)target;

        tk2dGuiUtility.LookLikeControls();

        GUILayout.Space(8);

        GUILayout.BeginVertical();

        GUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel("Direction");
        sizer.horizontal = GUILayout.Toolbar(sizer.horizontal ? 0 : 1, new string[] { "Horizontal", "Vertical" }) == 0;
        if (GUILayout.Button("R"))
        {
            GUI.changed = true;
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel(" ");
        sizer.expand = GUILayout.Toggle(sizer.expand, sizer.horizontal ? "Expand Vertical" : "Expand Horizontal");
        GUILayout.EndVertical();

        sizer.margin  = EditorGUILayout.Vector2Field("Margin", sizer.margin);
        sizer.spacing = EditorGUILayout.FloatField("Spacing", sizer.spacing);
        GUILayout.EndVertical();

        if (!allActive)
        {
            int addMode = tk2dGuiUtility.InfoBoxWithButtons("Not all children UI Layouts are included in the sizer.", tk2dGuiUtility.WarningLevel.Error, "Fixed Size", "Proportional");
            if (addMode != -1)
            {
                AddMissingLayoutChildren((addMode == 0));
                UpdateChildren();
                GUI.changed = true;
            }
        }
        else if (hasNonLayouts)
        {
            EditorGUILayout.HelpBox("The sizer contains non UI Layout children. These will not be affected by the sizer.", MessageType.Info);
        }

        base.OnInspectorGUI();

        if (GUI.changed)
        {
            sizer.Refresh();
            Object[] objs = EditorUtility.CollectDeepHierarchy(new Object[] { target });
            foreach (Object obj in objs)
            {
                EditorUtility.SetDirty(obj);
            }
        }
    }
Пример #11
0
 static Object[] CollectDeepHierarchy(GameObject go)
 {
     if (go == null)
     {
         return(new Object[0]);
     }
     else
     {
         return(EditorUtility.CollectDeepHierarchy(new Object[] { go }));
     }
 }
Пример #12
0
    /// <summary>
    /// Function that collects a list of file dependencies from the specified list of objects.
    /// </summary>

    static List <AssetEntry> GetDependencyList(Object[] objects, bool reverse)
    {
        Object[] deps = reverse ? EditorUtility.CollectDeepHierarchy(objects) : EditorUtility.CollectDependencies(objects);

        List <AssetEntry> list = new List <AssetEntry>();

        {
            var __array2       = deps;
            var __arrayLength2 = __array2.Length;
            for (int __i2 = 0; __i2 < __arrayLength2; ++__i2)
            {
                var obj = (Object)__array2[__i2];
                {
                    string path = AssetDatabase.GetAssetPath(obj);

                    if (!string.IsNullOrEmpty(path))
                    {
                        bool        found = false;
                        System.Type type  = obj.GetType();
                        {
                            var __list5      = list;
                            var __listCount5 = __list5.Count;
                            for (int __i5 = 0; __i5 < __listCount5; ++__i5)
                            {
                                var ent = (AssetEntry)__list5[__i5];
                                {
                                    if (ent.path.Equals(path))
                                    {
                                        if (!ent.types.Contains(type))
                                        {
                                            ent.types.Add(type);
                                        }
                                        found = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if (!found)
                        {
                            AssetEntry ent = new AssetEntry();
                            ent.path = path;
                            ent.types.Add(type);
                            list.Add(ent);
                        }
                    }
                }
            }
        }
        deps    = null;
        objects = null;
        return(list);
    }
 static void AddGameObjectsAndComponentsToManager()
 {
     if (refMgr != null)
     {
         foreach (var obj in EditorUtility.CollectDeepHierarchy(SceneManager.GetActiveScene().GetRootGameObjects()))
         {
             // If this object can be saved, add it to the reference manager.
             if (ES3ReferenceMgr.CanBeSaved(obj))
             {
                 refMgr.Add(obj);
             }
         }
         refMgr.AddPrefabsToManager();
     }
 }
Пример #14
0
    private void DrawDeepHierarchy()
    {
        GUILayout.Label("DeepHierarchy");
        var dependencies = EditorUtility.CollectDeepHierarchy(new[] { Selection.activeObject });

        foreach (var obj in dependencies)
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label(AssetDatabase.GetAssetPath(obj) + " : " + obj);
            if (GUILayout.Button("选择", GUILayout.Width(100)))
            {
                Selection.activeObject = obj;
            }
            EditorGUILayout.EndHorizontal();
        }
    }
Пример #15
0
        static internal void BuildLinks(this PELinkage _this, GameObject prefab)
        {
            var objects = EditorUtility.CollectDeepHierarchy(new Object[] { prefab });

            for (var i = 0; i < _this.Links.Count; i++)
            {
                var link = _this.Links[i];
                if (objects.Any(obj => obj == link.InstanceTarget))
                {
                    continue;
                }

                _this.Links.RemoveAt(i);
                i--;
            }

            _this.Add(prefab, objects);
        }
Пример #16
0
    public static bool DoPatch(Transform xffect)
    {
        XffectComponent xft = xffect.GetComponent <XffectComponent>();

        System.Version myVer = new System.Version(xft.MyVersion);

        if (xft != null && myVer >= new System.Version("4.4.0"))
        {
            return(false);
        }

        bool needToReimport = false;

        Object[] deps = EditorUtility.CollectDeepHierarchy(new Object[] { xffect.gameObject as Object });

        foreach (Object obj in deps)
        {
            if (obj == null || obj.GetType() != typeof(GameObject))
            {
                continue;
            }
            GameObject  go  = obj as GameObject;
            EffectLayer efl = go.GetComponent <EffectLayer>();
            if (efl != null)
            {
                DoPatch(efl);
                needToReimport = true;
            }

            XftEventComponent xevent = go.GetComponent <XftEventComponent>();
            if (xevent != null)
            {
                DoPatch(xevent);
                needToReimport = true;
            }
        }

        if (xft != null)
        {
            xft.MyVersion = XffectComponent.CurVersion;
        }

        return(needToReimport);
    }
Пример #17
0
    void DoPatch440(XffectComponent xffect)
    {
        xffect.MyVersion = XffectComponent.CurVersion;

        Object[] deps = EditorUtility.CollectDeepHierarchy(new Object[] { xffect.gameObject as Object });
        foreach (Object obj in deps)
        {
            if (obj == null || obj.GetType() != typeof(GameObject))
            {
                continue;
            }
            GameObject  go  = obj as GameObject;
            EffectLayer efl = go.GetComponent <EffectLayer>();
            if (efl != null)
            {
                DoPatch440(efl);
            }
        }
    }
Пример #18
0
    /// <summary>
    /// Function that collects a list of file dependencies from the specified list of objects.
    /// </summary>

    static List <AssetEntry> GetDependencyList(Object[] objects, bool reverse)
    {
        Object[] deps = reverse ? EditorUtility.CollectDeepHierarchy(objects) : EditorUtility.CollectDependencies(objects);

        List <AssetEntry> list = new List <AssetEntry>();

        foreach (Object obj in deps)
        {
            string path = AssetDatabase.GetAssetPath(obj);

            if (!string.IsNullOrEmpty(path))
            {
                bool        found = false;
                System.Type type  = obj.GetType();

                foreach (AssetEntry ent in list)
                {
                    if (ent.path.Equals(path))
                    {
                        if (!ent.types.Contains(type))
                        {
                            ent.types.Add(type);
                        }
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    AssetEntry ent = new AssetEntry();
                    ent.path = path;
                    ent.types.Add(type);
                    list.Add(ent);
                }
            }
        }

        deps    = null;
        objects = null;
        return(list);
    }
Пример #19
0
    // ------------------------------------------------------------------
    // Desc:
    // ------------------------------------------------------------------

    static void GetSpritesFromPrefabsInSelection(ref List <exSpriteBase> _sprites)
    {
        Object[] prefabs = Selection.GetFiltered(typeof(Texture2D), SelectionMode.DeepAssets);
        foreach (Object prefab in prefabs)
        {
            Object [] objs = EditorUtility.CollectDeepHierarchy(new Object [] { prefab });
            foreach (Object o in objs)
            {
                GameObject go = o as GameObject;
                if (go != null)
                {
                    exSpriteBase sp = go.GetComponent <exSpriteBase>();
                    if (sp != null)
                    {
                        _sprites.Add(sp);
                    }
                }
            }
        }
    }
        //Finds all serialized references from DEST to SRC (and their descendents and components) and
        //tries to fix any cross-references to point to the correct object in DEST instead. Logs fixed and unfixed references.
        void ProcessCrossReferencesInTree()
        {
            UnityEngine.Object[] fromHierarchy = EditorUtility.CollectDeepHierarchy(new UnityEngine.Object[] { treeRoot.remapTarget });
            UnityEngine.Object[] toHierarchy   = EditorUtility.CollectDeepHierarchy(new UnityEngine.Object[] { srcObj });
            var toHashSet     = new HashSet <UnityEngine.Object>(toHierarchy); //dump into hashset for fast finds
            var compToNodeMap = new Dictionary <Component, ModelTreeNode>();

            treeRoot.FillComponentToNodeMap(compToNodeMap);
            StringBuilder fixedRefLog   = new StringBuilder();
            StringBuilder unfixedRefLog = new StringBuilder();

            for (int i = 0; i < fromHierarchy.Length; i++)
            {
                if (fromHierarchy[i] is Component)
                {
                    ProcessReferencesInComponent(fromHierarchy[i] as Component, toHashSet, (comp, prop, objRef) => {
                        if (FixCrossReference(prop, refFixupMap, compToNodeMap))
                        {
                            fixedRefLog.AppendLine(comp.gameObject.name + " -> " + comp.GetType() + "." + prop.propertyPath);
                        }
                        else
                        {
                            unfixedRefLog.AppendLine(comp.gameObject.name + " -> " + comp.GetType() + "." + prop.propertyPath);
                        }
                        ;
                    });
                }
            }
            if (fixedRefLog.Length > 0)
            {
                fixedRefLog.Insert(0, "References to the source hierarchy discovered and fixed automatically:\n");
                Debug.Log(fixedRefLog.ToString());
            }
            if (unfixedRefLog.Length > 0)
            {
                unfixedRefLog.Insert(0, "References to the source hierarchy discovered and could not be fixed automatically:\n");
                Debug.LogWarning(unfixedRefLog.ToString());
            }
        }
Пример #21
0
        protected static void CleanupMissingScripts()
        {
            Object[] collectedDeepHierarchy     = EditorUtility.CollectDeepHierarchy(Selection.gameObjects);
            int      removedComponentsCounter   = 0;
            int      gameobjectsAffectedCounter = 0;

            foreach (Object targetObject in collectedDeepHierarchy)
            {
                if (targetObject is GameObject gameObject)
                {
                    int amountOfMissingScripts = GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(gameObject);
                    if (amountOfMissingScripts > 0)
                    {
                        Undo.RegisterCompleteObjectUndo(gameObject, "Removing missing scripts");
                        GameObjectUtility.RemoveMonoBehavioursWithMissingScript(gameObject);
                        removedComponentsCounter += amountOfMissingScripts;
                        gameobjectsAffectedCounter++;
                    }
                }
            }
            Debug.Log("[MMCleanupMissingScripts] Removed " + removedComponentsCounter + " missing scripts from " + gameobjectsAffectedCounter + " GameObjects");
        }
Пример #22
0
    private static void FindAndRemoveMissingInSelected()
    {
        var deepSelection = EditorUtility.CollectDeepHierarchy(Selection.gameObjects);
        int compCount     = 0;
        int goCount       = 0;

        foreach (var o in deepSelection)
        {
            if (o is GameObject go)
            {
                int count = GameObjectUtility.GetMonoBehavioursWithMissingScriptCount(go);
                if (count > 0)
                {
                    // Edit: use undo record object, since undo destroy wont work with missing
                    Undo.RegisterCompleteObjectUndo(go, "Remove missing scripts");
                    GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
                    compCount += count;
                    goCount++;
                }
            }
        }
        Debug.Log($"Found and removed {compCount} missing scripts from {goCount} GameObjects");
    }
Пример #23
0
        public static void CleanupMissingScriptsInTheActiveScene()
        {
            GameObject[] rootGameObjects = EditorSceneManager.GetActiveScene().GetRootGameObjects();

            if (rootGameObjects == null || rootGameObjects.Length == 0)
            {
                JSLDebug.Log("[ComponentUtils] - There is no gameObjects.");
                return;
            }

            Object[] result = EditorUtility.CollectDeepHierarchy(rootGameObjects);
            int      count  = 0;

            foreach (Object obj in result)
            {
                count++;

                if (obj == null)
                {
                    continue;
                }

                if (EditorUtility.DisplayCancelableProgressBar("Hold on...", string.Format("Cleanup Missing Scripts in object '{0}'...{1}/{2}", obj.name, count, result.Length), (float)count / result.Length))
                {
                    break;
                }

                if (obj is GameObject gameObject)
                {
                    RemoveMissingScript(gameObject);
                }
            }

            EditorUtility.ClearProgressBar();

            EditorSceneManager.SaveOpenScenes();
        }
Пример #24
0
    void OnGUI()
    {
        if (!Spline)
        {
            GUILayout.Label("Please select a Curvy Spline!", EditorStyles.boldLabel);
            return;
        }
        if (!Planar)
        {
            GUILayout.Label("Can't export! The spline needs to be planar!", EditorStyles.boldLabel);
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Equalize X"))
            {
                Undo.RegisterUndo(EditorUtility.CollectDeepHierarchy(new Object[] { Spline }), "Equalize X");
                CurvyUtility.makePlanar(Spline, 0);
            }
            if (GUILayout.Button("Equalize Y"))
            {
                Undo.RegisterUndo(EditorUtility.CollectDeepHierarchy(new Object[] { Spline }), "Equalize Y");
                CurvyUtility.makePlanar(Spline, 1);
            }
            if (GUILayout.Button("Equalize Z"))
            {
                Undo.RegisterUndo(EditorUtility.CollectDeepHierarchy(new Object[] { Spline }), "Equalize Z");
                CurvyUtility.makePlanar(Spline, 2);
            }
            GUILayout.EndHorizontal();
            return;
        }
        GUILayout.Label("Please note:", EditorStyles.boldLabel);
        GUILayout.Label("Depending on curvation and vertices settings the resulting mesh might produce errors when fed to the MeshBuilder as a custom shape! The triangulation process will be optimized in the future!", EditorStyles.wordWrappedLabel);
        GUILayout.Space(5);
        GUILayout.Label("Options", EditorStyles.boldLabel);
        MeshName     = EditorGUILayout.TextField("Object/Mesh Name", MeshName);
        MeshMaterial = EditorGUILayout.ObjectField(new GUIContent("Material"), MeshMaterial, typeof(Material), true) as Material;

        CalcMode = (VertexCalcMode)EditorGUILayout.EnumPopup(new GUIContent("Edge Vertices", "How to create Edge Vertices"), CalcMode);
        if (CalcMode == VertexCalcMode.AngleDiff)
        {
            calcAngle = EditorGUILayout.FloatField(new GUIContent("Angle", "Angle Difference"), calcAngle);
        }

        if (!Spline.Closed)
        {
            AutoClose = EditorGUILayout.Toggle(new GUIContent("Close Edge Loop", "Connect First&last edge vertex"), AutoClose);
        }
        if (GUILayout.Button("Preview"))
        {
            Triangulate();
        }
        if (Vertices.Length > 0)
        {
            GUILayout.Label(string.Format("Mesh Info: {0} Vertices, {1} Triangles", new object[] { Vertices.Length, Triangles.Length }));
        }
        GUILayout.Label("Export Mesh", EditorStyles.boldLabel);
        GUILayout.BeginHorizontal();

        if (GUILayout.Button("Save as Asset"))
        {
            string path = EditorUtility.SaveFilePanelInProject("Save Mesh", MeshName + ".asset", "asset", "Choose a file location");
            if (!string.IsNullOrEmpty(path))
            {
                Mesh msh = createMesh();
                if (msh)
                {
                    msh.name = MeshName;
                    AssetDatabase.DeleteAsset(path);
                    AssetDatabase.CreateAsset(msh, path);
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();
                    Debug.Log("Curvy Export: Mesh Asset saved!");
                }
                else
                {
                    Debug.LogWarning("Curvy Export: Unable to triangulate spline!");
                }
            }
        }

        if (GUILayout.Button("Create GameObject"))
        {
            Mesh msh = createMesh();
            if (msh)
            {
                msh.name = MeshName;
                var go = new GameObject(MeshName, typeof(MeshRenderer), typeof(MeshFilter));
                go.GetComponent <MeshFilter>().sharedMesh       = msh;
                go.GetComponent <MeshRenderer>().sharedMaterial = MeshMaterial;
                Selection.activeGameObject = go;
                Debug.Log("Curvy Export: GameObject created!");
            }
            else
            {
                Debug.LogWarning("Curvy Export: Unable to triangulate spline!");
            }
        }

        GUILayout.EndHorizontal();
        if (GUI.changed)
        {
            Triangulate();
        }
    }
Пример #25
0
    public void OnSceneGUI()
    {
        if (My.GetComponent <tk2dBaseSprite>() != null)
        {
            return;
        }

        Transform t = My.transform;

        DrawLayoutOutline(t);

        Rect r0 = new Rect(My.bMin.x, My.bMin.y, My.bMax.x - My.bMin.x, My.bMax.y - My.bMin.y);

        Handles.BeginGUI();
        Rect r1 = tk2dSceneHelper.RectControl("UILayout".GetHashCode(), r0, t);

        Handles.EndGUI();
        if (r0 != r1)
        {
            Vector3  dMin = new Vector3(r1.xMin - r0.xMin, r1.yMin - r0.yMin);
            Vector3  dMax = new Vector3(r1.xMax - r0.xMax, r1.yMax - r0.yMax);
            Object[] deps = EditorUtility.CollectDeepHierarchy(new Object[] { My });
            tk2dUndo.RecordObjects(deps, "Resize");
            My.Reshape(dMin, dMax, updateChildren);
            foreach (var dep in deps)
            {
                tk2dUtil.SetDirty(dep);
            }
        }

        Event ev = Event.current;

        if (ev.type == EventType.ValidateCommand && ev.commandName == "UndoRedoPerformed")
        {
            tk2dBaseSprite[] sprites = My.GetComponentsInChildren <tk2dBaseSprite>() as tk2dBaseSprite[];
            foreach (tk2dBaseSprite sprite in sprites)
            {
                sprite.ForceBuild();
            }
            tk2dTextMesh[] textMeshes = My.GetComponentsInChildren <tk2dTextMesh>() as tk2dTextMesh[];
            foreach (tk2dTextMesh textMesh in textMeshes)
            {
                textMesh.ForceBuild();
            }
        }

        // Draw outline of selected item
        if (selItem != null)
        {
            if (selItem.gameObj.GetComponent <Renderer>() != null || selItem.layout != null)
            {
                float   s    = HandleUtility.GetHandleSize(t.position) * 0.05f;
                Vector3 svec = new Vector3(s, s);
                Bounds  b    = new Bounds();
                if (selItem.layout != null)
                {
                    b.center = selItem.gameObj.transform.position + 0.5f * (selItem.layout.bMin + selItem.layout.bMax);
                    b.size   = selItem.layout.bMax - selItem.layout.bMin;
                }
                else
                {
                    b = selItem.gameObj.GetComponent <Renderer>().bounds;
                }
                Handles.color = Color.red;
                float[] kx = new float[] { -1, 1, 1, -1, -1 };
                float[] ky = new float[] { -1, -1, 1, 1, -1 };
                for (int k = 0; k < 4; ++k)
                {
                    Vector3 p1     = b.center + new Vector3(b.extents.x * kx[k], b.extents.y * ky[k]);
                    Vector3 p2     = b.center + new Vector3(b.extents.x * kx[k + 1], b.extents.y * ky[k + 1]);
                    int     nLines = (int)((p1 - p2).magnitude / s);
                    for (int i = 0; i < nLines; ++i)
                    {
                        Vector3 q = p1 + ((float)i / (float)nLines) * (p2 - p1);
                        Handles.DrawLine(q - svec, q + svec);
                    }
                }
            }
        }
    }
Пример #26
0
    public override void OnInspectorGUI()
    {
        GUILayout.Space(16);
        GUILayout.BeginVertical();

        if (My.GetComponent <tk2dBaseSprite>() != null || My.GetComponent <tk2dTextMesh>() != null || My.GetComponent <tk2dUIMask>() != null)
        {
            EditorGUILayout.HelpBox("Please remove Sprite/TextMesh/UIMask from this Object\nin order to use Layout!", MessageType.Error);
            GUILayout.EndVertical();
            return;
        }

        //My.bMin = EditorGUILayout.Vector3Field("bMin", My.bMin);
        //My.bMax = EditorGUILayout.Vector3Field("bMax", My.bMax);

        GUILayout.BeginHorizontal();

        int width = 96;

        GUILayout.BeginVertical();
        updateChildren = !GUILayout.Toggle(!updateChildren, "Edit Mode", "button", GUILayout.ExpandWidth(false), GUILayout.Width(width));
        bool editMode = !updateChildren;

        GUI.enabled = editMode;

        EditorGUI.indentLevel++;
        My.autoResizeCollider = EditorGUILayout.Toggle("Resize Collider", My.autoResizeCollider);

        GUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel("Fit Layout");
        if (GUILayout.Button("To Geometry", GUILayout.ExpandWidth(false), GUILayout.Width(width)))
        {
            int numInList = 0;
            foreach (tk2dUILayoutItem v in itemsList)
            {
                if (v.inLayoutList)
                {
                    numInList++;
                }
            }
            if (numInList == 0)
            {
                EditorUtility.DisplayDialog("Fit Layout", "Fit Layout requires items anchored in the layout.", "Ok");
            }
            else
            {
                Object[] deps = EditorUtility.CollectDeepHierarchy(new Object[] { My });
                tk2dUndo.RecordObjects(deps, "Resize");

                Vector3[] minMax = new Vector3[] { Vector3.one *float.MaxValue, Vector3.one * -float.MaxValue };
                GetChildRendererBounds(My.transform.worldToLocalMatrix, minMax, My.transform);
                Vector3 dMin = new Vector3(minMax[0].x - My.bMin.x, minMax[0].y - My.bMin.y);
                Vector3 dMax = new Vector3(minMax[1].x - My.bMax.x, minMax[1].y - My.bMax.y);

                bool    lastAutoResizeCollider = My.autoResizeCollider;
                Vector3 lastPos = My.transform.position;
                My.autoResizeCollider = false;
                My.Reshape(dMin, dMax, false);
                My.autoResizeCollider = lastAutoResizeCollider;
                var box = My.GetComponent <BoxCollider>();
                if (box != null)
                {
                    box.center -= My.transform.worldToLocalMatrix.MultiplyVector(My.transform.position - lastPos);
                }

                foreach (var dep in deps)
                {
                    tk2dUtil.SetDirty(dep);
                }
            }
        }
        GUILayout.EndHorizontal();
        EditorGUI.indentLevel--;
        GUI.enabled = true;

        GUILayout.EndVertical();

        GUILayout.FlexibleSpace();

        GUI.enabled = editMode && (selItem != null);
        ItemInspector(selItem);
        GUI.enabled = true;

        GUILayout.EndHorizontal();

        GUILayout.Space(4);

        bool   warnLayoutHasSprite = false;
        string warnLayoutName      = "";

        GUILayout.BeginVertical("box");
        foreach (var item in itemsList)
        {
            if (item.inLayoutList)
            {
                if (item.layout)
                {
                    GUI.color = new Color(1.0f, 1.0f, 0.3f);
                }
                else
                {
                    GUI.color = Color.green;
                }

                if (item.layout != null && item.gameObj.GetComponent <tk2dBaseSprite>() != null)
                {
                    warnLayoutHasSprite = true;
                    warnLayoutName      = item.gameObj.name;
                }
            }
            else
            {
                GUI.color = Color.white;
            }
            if (GUILayout.Toggle(item == selItem, item.gameObj.name, tk2dEditorSkin.SC_ListBoxItem))
            {
                if (selItem != item)
                {
                    EditorGUIUtility.PingObject(item.gameObj);
                    SceneView.RepaintAll();
                    Repaint();
                }
                selItem = item;
            }
        }
        GUILayout.EndVertical();
        GUI.color = Color.white;

        if (warnLayoutHasSprite)
        {
            EditorGUILayout.HelpBox("Child Layout with Sprite found. Cannot resize \"" + warnLayoutName + "\"", MessageType.Error);
        }

        ArrowKeyNav();

        GUILayout.Space(40);

        GUILayout.EndVertical();

        if (GUI.changed)
        {
            tk2dUtil.SetDirty(target);
        }
    }
Пример #27
0
        static private void CalculateStructureDiff(this PEModifications _this, PEPrefabScript prefab, PEPrefabScript instance)
        {
            _this.NonPrefabObjects.Clear();
            var hierarchy = EditorUtility.CollectDeepHierarchy(new[] { instance });

            foreach (var transform in hierarchy.OfType <Transform>())
            {
                if (transform.parent == null)
                {
                    continue;
                }

                var link = prefab.Links[instance.Links[transform]];
                if (link != null)
                {
                    continue;
                }

                _this.NonPrefabObjects.Add(new PEModifications.HierarchyData {
                    child  = transform,
                    parent = transform.parent
                });
            }

            _this.NonPrefabComponents.Clear();
            foreach (var component in hierarchy.Where(obj => !(obj is Transform)).OfType <Component>())
            {
                var link = prefab.Links[instance.Links[component]];
                if (link != null || prefab.Links[instance.Links[component.gameObject.transform]] == null)
                {
                    continue;
                }

                _this.NonPrefabComponents.Add(new PEModifications.ComponentsData {
                    child  = component,
                    parent = component.gameObject
                });
            }

            _this.RemovedObjects.Clear();
            foreach (var link in prefab.Links.Links)
            {
                if (link.InstanceTarget is Transform)
                {
                    continue;
                }

                if (instance.Links[link] == null || instance.Links[link].InstanceTarget == null)
                {
                    _this.RemovedObjects.Add(link.LIIF);
                }
            }

            _this.TransformParentChanges.Clear();
            foreach (var link in instance.Links.Links)
            {
                var transform = link.InstanceTarget as Transform;
                if (transform == null)
                {
                    continue;
                }

                var currentTransform = transform;
                if (currentTransform == instance.transform)
                {
                    continue;
                }

                var currentTransformParent = currentTransform.parent;
                if (prefab.Links[link] == null)
                {
                    continue;
                }

                var otherTransform = prefab.Links[link].InstanceTarget as Transform;

                var otherTransformParent = otherTransform.parent;

                if (prefab.Links[otherTransformParent] == null || instance.Links[currentTransformParent] == null ||
                    prefab.Links[otherTransformParent].LIIF
                    != instance.Links[currentTransformParent].LIIF)
                {
                    _this.TransformParentChanges.Add(new PEModifications.HierarchyData {
                        child  = currentTransform,
                        parent = currentTransformParent
                    });
                }
            }
        }
Пример #28
0
 static internal void ReplaceReference(Object root, IDictionary <Object, Object> dict)
 {
     ReplaceReference(EditorUtility.CollectDeepHierarchy(new [] { root }), dict);
 }
    public void CreatePublicPreset(bool isOverwrite)
    {
        // Create folders
        if (!isOverwrite && !createPackage)
        {
            AssetDatabase.CreateFolder("Assets", "Playground Preset - " + particleSystemName);
            AssetDatabase.CreateFolder("Assets/Playground Preset - " + particleSystemName, "Resources");
            AssetDatabase.CreateFolder("Assets/Playground Preset - " + particleSystemName + "Resources", "Csharp");
            AssetDatabase.CreateFolder("Assets/Playground Preset - " + particleSystemName + "/Resources/Csharp", "Presets");
        }

        // Path to the new resources/presets folder
        string publicPresetPath = "Assets/Playground Preset - " + particleSystemName + "/Resources/Presets/Csharp/";



        // Get dependencies
        List <string> presetDependencies = new List <string>();

        string[] tmpPresetDependencies = AssetDatabase.GetDependencies(new string[] { AssetDatabase.GetAssetPath(PlaygroundParticleWindowC.presetObjects[selectedPreset].presetObject as UnityEngine.Object) });

        // Copy the icon file
        if (!createPackage)
        {
            AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(particleSystemIcon as UnityEngine.Object), publicPresetPath + particleSystemName + ".png");
        }
        else
        {
            presetDependencies.Add(AssetDatabase.GetAssetPath(particleSystemIcon as UnityEngine.Object));
        }
        for (int i = 0; i < tmpPresetDependencies.Length; i++)
        {
            // Check that the operation won't disturb any of the unnecessary files from the framework
            if (!tmpPresetDependencies[i].Contains("PlaygroundBrushPresetInspectorC.cs") &&
                !tmpPresetDependencies[i].Contains("PlaygroundCreateBrushWindowC.cs") &&
                !tmpPresetDependencies[i].Contains("PlaygroundCreatePresetWindowC.cs") &&
                !tmpPresetDependencies[i].Contains("PlaygroundInspectorC.cs") &&
                !tmpPresetDependencies[i].Contains("PlaygroundParticleSystemInspectorC.cs") &&
                !tmpPresetDependencies[i].Contains("PlaygroundParticleWindowC.cs") &&
                !tmpPresetDependencies[i].Contains("PlaygroundBrushPresetC.cs")
                )
            {
                // It's the preset, rename if user specified another name
                if (Path.GetFileName(tmpPresetDependencies[i]) == PlaygroundParticleWindowC.presetNames[selectedPreset] + ".prefab" && particleSystemName != Path.GetFileName(tmpPresetDependencies[i]))
                {
                    AssetDatabase.Refresh();
                    AssetDatabase.RenameAsset(publicPresetPath + Path.GetFileName(tmpPresetDependencies[i]), particleSystemName);
                    tmpPresetDependencies[i] = Path.GetDirectoryName(tmpPresetDependencies[i]) + "/" + particleSystemName + ".prefab";
                }

                // Add to preset dependencies list
                presetDependencies.Add(tmpPresetDependencies[i]);
            }
        }

        // Check that necessary files are in
        if (!presetDependencies.Contains("PlaygroundC.cs"))
        {
            presetDependencies.Add(PlaygroundParticleWindowC.playgroundPath + PlaygroundParticleWindowC.scriptPath + "PlaygroundC.cs");
        }
        if (!presetDependencies.Contains("PlaygroundParticlesC.cs"))
        {
            presetDependencies.Add(PlaygroundParticleWindowC.playgroundPath + PlaygroundParticleWindowC.scriptPath + "PlaygroundParticlesC.cs");
        }
        if (!presetDependencies.Contains("Playground Manager"))
        {
            presetDependencies.Add(PlaygroundParticleWindowC.playgroundPath + "Resources/Csharp/Playground Manager.prefab");
        }

        // Refresh the project
        AssetDatabase.Refresh();

        // User wants to create a package of all dependency assets
        if (createPackage)
        {
            AssetDatabase.ExportPackage(presetDependencies.ToArray(), "Playground Preset - " + particleSystemName + ".unitypackage", ExportPackageOptions.Interactive);

            // All dependency assets will be moved instead
        }
        else
        {
            Undo.RecordObjects(EditorUtility.CollectDeepHierarchy(new Object[] { PlaygroundParticleWindowC.presetObjects[selectedPreset].presetObject as UnityEngine.Object }) as UnityEngine.Object[], "Move all dependencies of preset");
            for (int i = 0; i < presetDependencies.Count; i++)
            {
                AssetDatabase.MoveAsset(presetDependencies[i], publicPresetPath + Path.GetFileName(presetDependencies[i]));
            }

            // Select the prefab
            EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath(publicPresetPath + PlaygroundParticleWindowC.presetNames[selectedPreset] + ".prefab", typeof(UnityEngine.Object)) as UnityEngine.Object);
        }

        // Refresh the project
        AssetDatabase.Refresh();

        // Close window
        window.Close();
    }
        private Object  EditorResolveSlow()
        {
            var scene = this.scene.scene;

            if (!scene.IsValid())
            {
                return(null);
            }

            if (!scene.isLoaded)
            {
                return(null);
            }

            // Find the object (this is potentially very slow).
            Object[] allObjs = EditorUtility.CollectDeepHierarchy(scene.GetRootGameObjects());
            foreach (var obj in allObjs)
            {
                // Apparently this happens... bummer
                if (!obj)
                {
                    continue;
                }

                // If it's a prefab, it's a lot more difficult since Unity doesn't store IDs
                var prefabObj = PrefabUtility.GetPrefabObject(obj);
                if (prefabObj && editorLocalId == GetEditorId(prefabObj))
                {
                    GameObject gameObject = GameObjectEx.EditorGetGameObjectFromComponent(obj);
                    if (!gameObject)
                    {
                        Debug.LogWarningFormat(obj, "Could not SLOW resolve {0} (cross-scene reference is broken). Pointing it to {1}.", this, obj);
                        return(obj);
                    }

                    // Make sure we do this from the root
                    var prefabRoot = PrefabUtility.FindPrefabRoot(gameObject);
                    if (prefabRoot)
                    {
                        gameObject = prefabRoot;
                    }

                    // If we have a relative path, grab that GameObject
                    if (!string.IsNullOrEmpty(editorPrefabRelativePath))
                    {
                        Transform transform = gameObject.transform.Find(editorPrefabRelativePath);
                        if (transform)
                        {
                            gameObject = transform.gameObject;
                        }
                        else
                        {
                            Debug.LogWarningFormat(gameObject, "Tried to perform a slow resolve for {0} and found prefab {1}, but could not resolve the expected sub-path {2} which indicates the Prefab instance path was renamed.", this, gameObject, editorPrefabRelativePath);
                        }
                    }

                    Debug.LogWarningFormat(gameObject, "Performed a slow resolve on {0} due to a rename.  We found PREFAB with same ID named {1} (but we're not sure). Attempting a resolve with it.", this, gameObject);
                    fullPath = GameObjectEx.GetFullName(gameObject);
                    return(RuntimeResolve());
                }
                else if (editorLocalId == GetEditorId(obj))
                {
                    GameObject gameObject = GameObjectEx.EditorGetGameObjectFromComponent(obj);
                    Debug.LogWarningFormat(obj, "Performed a slow resolve on {0} and found {1} ({2}). Double-check this is correct.", this, gameObject ? gameObject.GetFullName() : "(Non-Existant GameObject)", obj.GetType());
                    return(obj);
                }
            }

            return(null);
        }