Ejemplo n.º 1
0
 public static void HandleSpriteSceneDrag(SceneView sceneView, IEvent evt, UnityEngine.Object[] objectReferences, string[] paths, SpriteUtility.ShowFileDialogDelegate saveFileDialog)
 {
     if (evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform || evt.type == EventType.DragExited)
     {
         if (!objectReferences.Any((UnityEngine.Object obj) => obj == null))
         {
             if (objectReferences.Length == 1 && objectReferences[0] as UnityEngine.Texture2D != null)
             {
                 GameObject gameObject = HandleUtility.PickGameObject(evt.mousePosition, true);
                 if (gameObject != null)
                 {
                     Renderer component = gameObject.GetComponent <Renderer>();
                     if (component != null && !(component is SpriteRenderer))
                     {
                         SpriteUtility.CleanUp(true);
                         return;
                     }
                 }
             }
             EventType type = evt.type;
             if (type != EventType.DragUpdated)
             {
                 if (type != EventType.DragPerform)
                 {
                     if (type == EventType.DragExited)
                     {
                         if (SpriteUtility.s_SceneDragObjects != null)
                         {
                             SpriteUtility.CleanUp(true);
                             evt.Use();
                         }
                     }
                 }
                 else
                 {
                     List <Sprite> spriteFromPathsOrObjects = SpriteUtility.GetSpriteFromPathsOrObjects(objectReferences, paths, evt.type);
                     if (spriteFromPathsOrObjects.Count > 0 && SpriteUtility.s_SceneDragObjects != null)
                     {
                         int currentGroup = Undo.GetCurrentGroup();
                         if (SpriteUtility.s_SceneDragObjects.Count == 0)
                         {
                             SpriteUtility.CreateSceneDragObjects(spriteFromPathsOrObjects);
                             SpriteUtility.PositionSceneDragObjects(SpriteUtility.s_SceneDragObjects, sceneView, evt.mousePosition);
                         }
                         using (List <UnityEngine.Object> .Enumerator enumerator = SpriteUtility.s_SceneDragObjects.GetEnumerator())
                         {
                             while (enumerator.MoveNext())
                             {
                                 GameObject gameObject2 = (GameObject)enumerator.Current;
                                 gameObject2.hideFlags = HideFlags.None;
                                 Undo.RegisterCreatedObjectUndo(gameObject2, "Create Sprite");
                                 EditorUtility.SetDirty(gameObject2);
                             }
                         }
                         bool flag = true;
                         if (SpriteUtility.s_DragType == SpriteUtility.DragType.SpriteAnimation && spriteFromPathsOrObjects.Count > 1)
                         {
                             UsabilityAnalytics.Event("Sprite Drag and Drop", "Drop multiple sprites to scene", "null", 1);
                             flag = SpriteUtility.AddAnimationToGO((GameObject)SpriteUtility.s_SceneDragObjects[0], spriteFromPathsOrObjects.ToArray(), saveFileDialog);
                         }
                         else
                         {
                             UsabilityAnalytics.Event("Sprite Drag and Drop", "Drop single sprite to scene", "null", 1);
                         }
                         if (flag)
                         {
                             Selection.objects = SpriteUtility.s_SceneDragObjects.ToArray();
                         }
                         else
                         {
                             Undo.RevertAllDownToGroup(currentGroup);
                         }
                         SpriteUtility.CleanUp(!flag);
                         evt.Use();
                     }
                 }
             }
             else
             {
                 SpriteUtility.DragType dragType = (!evt.alt) ? SpriteUtility.DragType.SpriteAnimation : SpriteUtility.DragType.CreateMultiple;
                 if (SpriteUtility.s_DragType != dragType || SpriteUtility.s_SceneDragObjects == null)
                 {
                     if (!SpriteUtility.ExistingAssets(objectReferences) && SpriteUtility.PathsAreValidTextures(paths))
                     {
                         DragAndDrop.visualMode           = DragAndDropVisualMode.Copy;
                         SpriteUtility.s_SceneDragObjects = new List <UnityEngine.Object>();
                         SpriteUtility.s_DragType         = dragType;
                     }
                     else
                     {
                         List <Sprite> spriteFromPathsOrObjects2 = SpriteUtility.GetSpriteFromPathsOrObjects(objectReferences, paths, evt.type);
                         if (spriteFromPathsOrObjects2.Count == 0)
                         {
                             return;
                         }
                         if (SpriteUtility.s_DragType != SpriteUtility.DragType.NotInitialized)
                         {
                             SpriteUtility.CleanUp(true);
                         }
                         SpriteUtility.s_DragType = dragType;
                         SpriteUtility.CreateSceneDragObjects(spriteFromPathsOrObjects2);
                         SpriteUtility.IgnoreForRaycasts(SpriteUtility.s_SceneDragObjects);
                     }
                 }
                 SpriteUtility.PositionSceneDragObjects(SpriteUtility.s_SceneDragObjects, sceneView, evt.mousePosition);
                 DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                 evt.Use();
             }
         }
     }
 }
Ejemplo n.º 2
0
        internal void Show(UnityObject obj, Type[] requiredTypes, UnityObject objectBeingEdited, bool allowSceneObjects, List <int> allowedInstanceIDs = null, Action <UnityObject> onObjectSelectorClosed = null, Action <UnityObject> onObjectSelectedUpdated = null)
        {
            m_ObjectSelectorReceiver = null;
            m_AllowSceneObjects      = allowSceneObjects;
            m_IsShowingAssets        = true;
            m_SkipHiddenPackages     = true;
            m_AllowedIDs             = allowedInstanceIDs;
            m_ObjectBeingEdited      = objectBeingEdited;
            m_LastSelectedInstanceId = obj?.GetInstanceID() ?? 0;

            m_OnObjectSelectorClosed  = onObjectSelectorClosed;
            m_OnObjectSelectorUpdated = onObjectSelectedUpdated;

            // Do not allow to show scene objects if the object being edited is persistent
            if (m_ObjectBeingEdited != null && EditorUtility.IsPersistent(m_ObjectBeingEdited))
            {
                m_AllowSceneObjects = false;
            }

            // Set which tab should be visible at startup
            if (m_AllowSceneObjects)
            {
                if (obj != null)
                {
                    if (typeof(Component).IsAssignableFrom(obj.GetType()))
                    {
                        obj = ((Component)obj).gameObject;
                    }
                    // Set the right tab visible (so we can see our selection)
                    m_IsShowingAssets = EditorUtility.IsPersistent(obj);
                }
                else
                {
                    foreach (var requiredType in requiredTypes)
                    {
                        m_IsShowingAssets &= (requiredType != typeof(GameObject) && !typeof(Component).IsAssignableFrom(requiredType));
                    }
                }
            }
            else
            {
                m_IsShowingAssets = true;
            }

            // Set member variables
            m_DelegateView = GUIView.current;
            // type filter requires unqualified names for built-in types, but will prioritize them over user types, so ensure user types are namespace-qualified
            if (m_RequiredTypes == null)
            {
                m_RequiredTypes = new string[requiredTypes.Length];
            }
            for (int i = 0; i < requiredTypes.Length; i++)
            {
                if (requiredTypes[i] != null)
                {
                    m_RequiredTypes[i] = typeof(ScriptableObject).IsAssignableFrom(requiredTypes[i]) || typeof(MonoBehaviour).IsAssignableFrom(requiredTypes[i]) ? requiredTypes[i].FullName : requiredTypes[i].Name;
                }
            }
            m_SearchFilter      = "";
            m_OriginalSelection = obj;
            m_ModalUndoGroup    = Undo.GetCurrentGroup();

            // Show custom selector if available
            if (ObjectSelectorSearch.HasEngineOverride())
            {
                m_SearchSessionHandler.BeginSession(() =>
                {
                    return(new SearchService.ObjectSelectorSearchContext
                    {
                        currentObject = obj,
                        editedObjects = m_EditedProperty != null ? m_EditedProperty.serializedObject.targetObjects : new[] { objectBeingEdited },
                        requiredTypes = requiredTypes,
                        requiredTypeNames = m_RequiredTypes,
                        allowedInstanceIds = allowedInstanceIDs,
                        visibleObjects = allowSceneObjects ? SearchService.VisibleObjects.All : SearchService.VisibleObjects.Assets,
                    });
                });

                Action <UnityObject> onSelectionChanged = selectedObj =>
                {
                    m_LastSelectedInstanceId = selectedObj == null ? 0 : selectedObj.GetInstanceID();
                    NotifySelectionChanged(false);
                };
                Action <UnityObject, bool> onSelectorClosed = (selectedObj, canceled) =>
                {
                    m_SearchSessionHandler.EndSession();
                    if (canceled)
                    {
                        // Undo changes we have done in the ObjectSelector
                        Undo.RevertAllDownToGroup(m_ModalUndoGroup);
                        m_LastSelectedInstanceId = 0;
                    }
                    else
                    {
                        m_LastSelectedInstanceId = selectedObj == null ? 0 : selectedObj.GetInstanceID();
                        NotifySelectionChanged(false);
                    }

                    m_EditedProperty = null;
                    NotifySelectorClosed(false);
                };

                if (m_SearchSessionHandler.SelectObject(onSelectorClosed, onSelectionChanged))
                {
                    return;
                }
                else
                {
                    m_SearchSessionHandler.EndSession();
                }
            }

            // Freeze to prevent flicker on OSX.
            // Screen will be updated again when calling
            // SetFreezeDisplay(false) further down.
            ContainerWindow.SetFreezeDisplay(true);

            ShowWithMode(ShowMode.AuxWindow);
            string text = "Select " + (requiredTypes[0] == null ? m_RequiredTypes[0] : requiredTypes[0].Name);

            for (int i = 1; i < requiredTypes.Length; i++)
            {
                text += (i == requiredTypes.Length - 1 ? " or " : ", ") + (requiredTypes[i] == null ? m_RequiredTypes[i] : requiredTypes[i].Name);
            }
            titleContent = EditorGUIUtility.TrTextContent(text);

            // Deal with window size
            Rect p = m_Parent == null ? new Rect(0, 0, 1, 1) : m_Parent.window.position;

            p.width  = EditorPrefs.GetFloat("ObjectSelectorWidth", 200);
            p.height = EditorPrefs.GetFloat("ObjectSelectorHeight", 390);
            position = p;
            minSize  = new Vector2(kMinWidth, kMinTopSize + kPreviewExpandedAreaHeight + 2 * kPreviewMargin);
            maxSize  = new Vector2(10000, 10000);
            SetupPreview();

            // Focus
            Focus();
            ContainerWindow.SetFreezeDisplay(false);

            m_FocusSearchFilter = true;

            // Add after unfreezing display because AuxWindowManager.cpp assumes that aux windows are added after we get 'got/lost'- focus calls.
            if (m_Parent != null)
            {
                m_Parent.AddToAuxWindowList();
            }

            // Initial selection
            int initialSelection = obj != null?obj.GetInstanceID() : 0;

            if (initialSelection != 0)
            {
                var assetPath = AssetDatabase.GetAssetPath(initialSelection);
                if (m_SkipHiddenPackages && !PackageManagerUtilityInternal.IsPathInVisiblePackage(assetPath))
                {
                    m_SkipHiddenPackages = false;
                }
            }

            if (m_RequiredTypes.All(t => ShouldTreeViewBeUsed(t)))
            {
                m_ObjectTreeWithSearch.Init(position, this, CreateAndSetTreeView, TreeViewSelection, ItemWasDoubleClicked, initialSelection, 0);
            }
            else
            {
                // To frame the selected item we need to wait to initialize the search until our window has been setup
                InitIfNeeded();
                m_ListArea.InitSelection(new[] { initialSelection });
                if (initialSelection != 0)
                {
                    m_ListArea.Frame(initialSelection, true, false);
                }
            }
        }
Ejemplo n.º 3
0
        internal void Show(UnityEngine.Object obj, Type requiredType, SerializedProperty property, bool allowSceneObjects, List <int> allowedInstanceIDs)
        {
            this.m_AllowSceneObjects = allowSceneObjects;
            this.m_IsShowingAssets   = true;
            this.m_AllowedIDs        = allowedInstanceIDs;
            string text = string.Empty;

            if (property != null)
            {
                text = property.objectReferenceTypeString;
                obj  = property.objectReferenceValue;
                UnityEngine.Object targetObject = property.serializedObject.targetObject;
                if (targetObject != null && EditorUtility.IsPersistent(targetObject))
                {
                    this.m_AllowSceneObjects = false;
                }
            }
            else
            {
                if (requiredType != null)
                {
                    text = requiredType.Name;
                }
            }
            if (this.m_AllowSceneObjects)
            {
                if (obj != null)
                {
                    if (typeof(Component).IsAssignableFrom(obj.GetType()))
                    {
                        obj = ((Component)obj).gameObject;
                    }
                    this.m_IsShowingAssets = (EditorUtility.IsPersistent(obj) || ObjectSelector.GuessIfUserIsLookingForAnAsset(text, false));
                }
                else
                {
                    this.m_IsShowingAssets = ObjectSelector.GuessIfUserIsLookingForAnAsset(text, true);
                }
            }
            else
            {
                this.m_IsShowingAssets = true;
            }
            this.m_DelegateView      = GUIView.current;
            this.m_RequiredType      = text;
            this.m_SearchFilter      = string.Empty;
            this.m_OriginalSelection = obj;
            this.m_ModalUndoGroup    = Undo.GetCurrentGroup();
            ContainerWindow.SetFreezeDisplay(true);
            base.ShowWithMode(ShowMode.AuxWindow);
            base.title = "Select " + text;
            Rect position = this.m_Parent.window.position;

            position.width  = EditorPrefs.GetFloat("ObjectSelectorWidth", 200f);
            position.height = EditorPrefs.GetFloat("ObjectSelectorHeight", 390f);
            base.position   = position;
            base.minSize    = new Vector2(200f, 335f);
            base.maxSize    = new Vector2(10000f, 10000f);
            this.SetupPreview();
            base.Focus();
            ContainerWindow.SetFreezeDisplay(false);
            this.m_FocusSearchFilter = true;
            this.m_Parent.AddToAuxWindowList();
            int num = (!(obj != null)) ? 0 : obj.GetInstanceID();

            if (property != null && property.hasMultipleDifferentValues)
            {
                num = 0;
            }
            if (ObjectSelector.ShouldTreeViewBeUsed(text))
            {
                this.m_ObjectTreeWithSearch.Init(base.position, this, new UnityAction <ObjectTreeForSelector.TreeSelectorData>(this.CreateAndSetTreeView), new UnityAction <TreeViewItem>(this.TreeViewSelection), new UnityAction(this.ItemWasDoubleClicked), num, 0);
            }
            else
            {
                this.InitIfNeeded();
                this.m_ListArea.InitSelection(new int[]
                {
                    num
                });
                if (num != 0)
                {
                    this.m_ListArea.Frame(num, true, false);
                }
            }
        }
Ejemplo n.º 4
0
        void HandleDragPerformEvent(Editor[] editors, Event evt, ref int targetIndex)
        {
            if (targetIndex != -1)
            {
                var draggingMode = DragAndDrop.GetGenericData(k_DraggingModeKey) as DraggingMode ? ;
                if (!draggingMode.HasValue || draggingMode.Value == DraggingMode.NotApplicable)
                {
                    targetIndex = -1;
                    return;
                }

                if (!editors[targetIndex].targets.All(t => t is Component))
                {
                    return;
                }

                var targetComponents = editors[targetIndex].targets.Cast <Component>().ToArray();

                if (draggingMode.Value == DraggingMode.Script)
                {
                    var scripts = DragAndDrop.objectReferences.Cast <MonoScript>();

                    // Ensure all script components can be added
                    var valid = true;
                    foreach (var targetComponent in targetComponents)
                    {
                        var gameObject = targetComponent.gameObject;
                        if (scripts.Any(s => !ComponentUtility.WarnCanAddScriptComponent(gameObject, s)))
                        {
                            valid = false;
                            break;
                        }
                    }

                    if (valid)
                    {
                        Undo.IncrementCurrentGroup();
                        var undoGroup = Undo.GetCurrentGroup();

                        // Add script components
                        var index           = 0;
                        var addedComponents = new Component[targetComponents.Length * scripts.Count()];
                        for (int i = 0; i < targetComponents.Length; i++)
                        {
                            var  targetComponent   = targetComponents[i];
                            var  gameObject        = targetComponent.gameObject;
                            bool targetIsTransform = targetComponent is Transform;
                            foreach (var script in scripts)
                            {
                                addedComponents[index++] = ObjectFactory.AddComponent(gameObject, script.GetClass());
                            }

                            // If the target is a Transform, the AddComponent might have replaced it with a RectTransform.
                            // Handle this possibility by updating the target component.
                            if (targetIsTransform)
                            {
                                targetComponents[i] = gameObject.transform;
                            }
                        }

                        // Move added components relative to target components
                        if (!ComponentUtility.MoveComponentsRelativeToComponents(addedComponents, targetComponents, m_TargetAbove))
                        {
                            // Ensure we have the same selection after calling RevertAllDownToGroup below (MoveComponentsRelativeToComponents can have opened a Prefab in Prefab Mode and changed selection to that root)
                            var wantedSelectedGameObject = Selection.activeGameObject;

                            // Revert added components if move operation fails (e.g. user has been shown the dialog with 'prefab instance restructuring is not posssible' or object is not editable)
                            Undo.RevertAllDownToGroup(undoGroup);

                            if (wantedSelectedGameObject != Selection.activeGameObject)
                            {
                                Selection.activeGameObject = wantedSelectedGameObject;
                            }
                        }
                    }
                }
                else
                {
                    // Handle dragging components
                    var sourceComponents = DragAndDrop.objectReferences.Cast <Component>().ToArray();
                    if (sourceComponents.Length == 0 || targetComponents.Length == 0)
                    {
                        return;
                    }

                    MoveOrCopyComponents(sourceComponents, targetComponents, EditorUtility.EventHasDragCopyModifierPressed(evt), false);
                }

                targetIndex = -1;
                DragAndDrop.AcceptDrag();
                evt.Use();
                EditorGUIUtility.ExitGUI();
            }
        }
Ejemplo n.º 5
0
        internal void Show(UnityObject obj, Type requiredType, SerializedProperty property, bool allowSceneObjects, List <int> allowedInstanceIDs, Action <UnityObject> onObjectSelectorClosed, Action <UnityObject> onObjectSelectedUpdated)
        {
            m_ObjectSelectorReceiver = null;
            m_AllowSceneObjects      = allowSceneObjects;
            m_IsShowingAssets        = true;
            m_SkipHiddenPackages     = true;
            m_AllowedIDs             = allowedInstanceIDs;

            m_OnObjectSelectorClosed  = onObjectSelectorClosed;
            m_OnObjectSelectorUpdated = onObjectSelectedUpdated;

            if (property != null)
            {
                if (requiredType == null)
                {
                    ScriptAttributeUtility.GetFieldInfoFromProperty(property, out requiredType);
                    // case 951876: built-in types do not actually have reflectable fields, so their object types must be extracted from the type string
                    // this works because built-in types will only ever have serialized references to other built-in types, which this window's filter expects as unqualified names
                    if (requiredType == null)
                    {
                        m_RequiredType = s_MatchPPtrTypeName.Match(property.type).Groups[1].Value;
                    }
                }

                obj = property.objectReferenceValue;
                m_ObjectBeingEdited = property.serializedObject.targetObject;

                // Do not allow to show scene objects if the object being edited is persistent
                if (m_ObjectBeingEdited != null && EditorUtility.IsPersistent(m_ObjectBeingEdited))
                {
                    m_AllowSceneObjects = false;
                }
            }

            // Set which tab should be visible at startup
            if (m_AllowSceneObjects)
            {
                if (obj != null)
                {
                    if (typeof(Component).IsAssignableFrom(obj.GetType()))
                    {
                        obj = ((Component)obj).gameObject;
                    }
                    // Set the right tab visible (so we can see our selection)
                    m_IsShowingAssets = EditorUtility.IsPersistent(obj);
                }
                else
                {
                    m_IsShowingAssets = (requiredType != typeof(GameObject) && !typeof(Component).IsAssignableFrom(requiredType));
                }
            }
            else
            {
                m_IsShowingAssets = true;
            }

            // Set member variables
            m_DelegateView = GUIView.current;
            // type filter requires unqualified names for built-in types, but will prioritize them over user types, so ensure user types are namespace-qualified
            if (requiredType != null)
            {
                m_RequiredType = typeof(ScriptableObject).IsAssignableFrom(requiredType) || typeof(MonoBehaviour).IsAssignableFrom(requiredType) ? requiredType.FullName : requiredType.Name;
            }
            m_SearchFilter      = "";
            m_OriginalSelection = obj;
            m_ModalUndoGroup    = Undo.GetCurrentGroup();

            // Freeze to prevent flicker on OSX.
            // Screen will be updated again when calling
            // SetFreezeDisplay(false) further down.
            ContainerWindow.SetFreezeDisplay(true);

            ShowWithMode(ShowMode.AuxWindow);
            titleContent = EditorGUIUtility.TrTextContent("Select " + (requiredType == null ? m_RequiredType : requiredType.Name));

            // Deal with window size
            Rect p = m_Parent == null ? new Rect(0, 0, 1, 1) : m_Parent.window.position;

            p.width  = EditorPrefs.GetFloat("ObjectSelectorWidth", 200);
            p.height = EditorPrefs.GetFloat("ObjectSelectorHeight", 390);
            position = p;
            minSize  = new Vector2(kMinWidth, kMinTopSize + kPreviewExpandedAreaHeight + 2 * kPreviewMargin);
            maxSize  = new Vector2(10000, 10000);
            SetupPreview();

            // Focus
            Focus();
            ContainerWindow.SetFreezeDisplay(false);

            m_FocusSearchFilter = true;

            // Add after unfreezing display because AuxWindowManager.cpp assumes that aux windows are added after we get 'got/lost'- focus calls.
            if (m_Parent != null)
            {
                m_Parent.AddToAuxWindowList();
            }

            // Initial selection
            int initialSelection = obj != null?obj.GetInstanceID() : 0;

            if (property != null && property.hasMultipleDifferentValues)
            {
                initialSelection = 0; // don't select anything on multi selection
            }
            if (initialSelection != 0)
            {
                var assetPath = AssetDatabase.GetAssetPath(initialSelection);
                if (m_SkipHiddenPackages && !PackageManagerUtilityInternal.IsPathInVisiblePackage(assetPath))
                {
                    m_SkipHiddenPackages = false;
                }
            }

            if (ShouldTreeViewBeUsed(m_RequiredType))
            {
                m_ObjectTreeWithSearch.Init(position, this, CreateAndSetTreeView, TreeViewSelection, ItemWasDoubleClicked, initialSelection, 0);
            }
            else
            {
                // To frame the selected item we need to wait to initialize the search until our window has been setup
                InitIfNeeded();
                m_ListArea.InitSelection(new[] { initialSelection });
                if (initialSelection != 0)
                {
                    m_ListArea.Frame(initialSelection, true, false);
                }
            }
        }
        void HandleEditorDragging(Editor[] editors, int editorIndex, Rect targetRect, float markerY, bool bottomTarget)
        {
            var evt = Event.current;

            switch (evt.type)
            {
            case EventType.DragUpdated:
                if (targetRect.Contains(evt.mousePosition))
                {
                    var draggingMode = DragAndDrop.GetGenericData(k_DraggingModeKey) as DraggingMode ? ;
                    if (!draggingMode.HasValue)
                    {
                        var draggedObjects = DragAndDrop.objectReferences;

                        if (draggedObjects.Length == 0)
                        {
                            draggingMode = DraggingMode.NotApplicable;
                        }
                        else if (draggedObjects.All(o => o is Component && !(o is Transform)))
                        {
                            draggingMode = DraggingMode.Component;
                        }
                        else if (draggedObjects.All(o => o is MonoScript))
                        {
                            draggingMode = DraggingMode.Script;
                        }
                        else
                        {
                            draggingMode = DraggingMode.NotApplicable;
                        }

                        DragAndDrop.SetGenericData(k_DraggingModeKey, draggingMode);
                    }

                    if (draggingMode.Value != DraggingMode.NotApplicable)
                    {
                        if (bottomTarget)
                        {
                            m_TargetAbove = false;
                            m_TargetIndex = m_LastIndex;
                        }
                        else
                        {
                            m_TargetAbove = evt.mousePosition.y < targetRect.y + targetRect.height / 2f;
                            m_TargetIndex = editorIndex;

                            if (m_TargetAbove)
                            {
                                m_TargetIndex++;
                                while (m_TargetIndex < editors.Length && m_InspectorWindow.ShouldCullEditor(editors, m_TargetIndex))
                                {
                                    m_TargetIndex++;
                                }

                                if (m_TargetIndex == editors.Length)
                                {
                                    m_TargetIndex = -1;
                                    return;
                                }
                            }
                        }

                        if (m_TargetAbove && m_InspectorWindow.EditorHasLargeHeader(m_TargetIndex, editors))
                        {
                            m_TargetIndex--;
                            while (m_TargetIndex >= 0 && m_InspectorWindow.ShouldCullEditor(editors, m_TargetIndex))
                            {
                                m_TargetIndex--;
                            }

                            if (m_TargetIndex == -1)
                            {
                                return;
                            }

                            m_TargetAbove = false;
                        }

                        if (draggingMode.Value == DraggingMode.Script)
                        {
                            // Validate dragging scripts
                            // Always allow script dragging, instead fail during DragPerform with a dialog box
                            DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                        }
                        else
                        {
                            // Validate dragging components
                            var valid = false;
                            if (editors[m_TargetIndex].targets.All(t => t is Component))
                            {
                                var targetComponents = editors[m_TargetIndex].targets.Cast <Component>().ToArray();
                                var sourceComponents = DragAndDrop.objectReferences.Cast <Component>().ToArray();
                                valid = MoveOrCopyComponents(sourceComponents, targetComponents, EditorUtility.EventHasDragCopyModifierPressed(evt), true);
                            }

                            if (valid)
                            {
                                DragAndDrop.visualMode = EditorUtility.EventHasDragCopyModifierPressed(evt) ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Move;
                            }
                            else
                            {
                                DragAndDrop.visualMode = DragAndDropVisualMode.None;
                                m_TargetIndex          = -1;
                                return;
                            }
                        }

                        evt.Use();
                    }
                }
                else
                {
                    m_TargetIndex = -1;
                }
                break;

            case EventType.DragPerform:
                if (m_TargetIndex != -1)
                {
                    var draggingMode = DragAndDrop.GetGenericData(k_DraggingModeKey) as DraggingMode ? ;
                    if (!draggingMode.HasValue || draggingMode.Value == DraggingMode.NotApplicable)
                    {
                        m_TargetIndex = -1;
                        return;
                    }

                    if (!editors[m_TargetIndex].targets.All(t => t is Component))
                    {
                        return;
                    }

                    var targetComponents = editors[m_TargetIndex].targets.Cast <Component>().ToArray();

                    if (draggingMode.Value == DraggingMode.Script)
                    {
                        var scripts = DragAndDrop.objectReferences.Cast <MonoScript>();

                        // Ensure all script components can be added
                        var valid = true;
                        foreach (var targetComponent in targetComponents)
                        {
                            var gameObject = targetComponent.gameObject;
                            if (scripts.Any(s => !ComponentUtility.WarnCanAddScriptComponent(targetComponent.gameObject, s)))
                            {
                                valid = false;
                                break;
                            }
                        }

                        if (valid)
                        {
                            Undo.IncrementCurrentGroup();
                            var undoGroup = Undo.GetCurrentGroup();

                            // Add script components
                            var index           = 0;
                            var addedComponents = new Component[targetComponents.Length * scripts.Count()];
                            foreach (var targetComponent in targetComponents)
                            {
                                var gameObject = targetComponent.gameObject;
                                foreach (var script in scripts)
                                {
                                    addedComponents[index++] = ObjectFactory.AddComponent(gameObject, script.GetClass());
                                }
                            }

                            // Move added components relative to target components
                            if (!ComponentUtility.MoveComponentsRelativeToComponents(addedComponents, targetComponents, m_TargetAbove))
                            {
                                // Revert added components if move operation fails (e.g. user aborts when asked to break prefab instance)
                                Undo.RevertAllDownToGroup(undoGroup);
                            }
                        }
                    }
                    else
                    {
                        // Handle dragging components
                        var sourceComponents = DragAndDrop.objectReferences.Cast <Component>().ToArray();
                        if (sourceComponents.Length == 0 || targetComponents.Length == 0)
                        {
                            return;
                        }

                        MoveOrCopyComponents(sourceComponents, targetComponents, EditorUtility.EventHasDragCopyModifierPressed(evt), false);
                    }

                    m_TargetIndex = -1;
                    DragAndDrop.AcceptDrag();
                    evt.Use();
                    EditorGUIUtility.ExitGUI();
                }
                break;

            case EventType.DragExited:
                m_TargetIndex = -1;
                break;

            case EventType.Repaint:
                if (m_TargetIndex != -1 && targetRect.Contains(evt.mousePosition))
                {
                    var markerRect = new Rect(targetRect.x, markerY, targetRect.width, 3f);
                    if (!m_TargetAbove)
                    {
                        markerRect.y += 2f;
                    }

                    Styles.insertionMarker.Draw(markerRect, false, false, false, false);
                }
                break;
            }
        }
Ejemplo n.º 7
0
        public static void HandleSpriteSceneDrag(SceneView sceneView, IEvent evt, Object[] objectReferences, string[] paths, ShowFileDialogDelegate saveFileDialog)
        {
            if (evt.type != EventType.DragUpdated && evt.type != EventType.DragPerform && evt.type != EventType.DragExited)
            {
                return;
            }

            // Return if any of the dragged objects are null, e.g. a MonoBehaviour without a managed instance
            if (objectReferences.Any(obj => obj == null))
            {
                return;
            }

            // Regardless of EditorBehaviorMode or SceneView mode we don't handle if texture is dragged over a GO with renderer
            if (objectReferences.Length == 1 && objectReferences[0] as UnityTexture2D != null)
            {
                GameObject go = HandleUtility.PickGameObject(evt.mousePosition, true);
                if (go != null)
                {
                    var renderer = go.GetComponent <Renderer>();
                    if (renderer != null && !(renderer is SpriteRenderer))
                    {
                        // There is an object where the cursor is
                        // and we are dragging a texture. Most likely user wants to
                        // assign texture to the GO
                        // Case 730444: Proceed only if the go has a renderer
                        CleanUp(true);
                        return;
                    }
                }
            }

            switch (evt.type)
            {
            case (EventType.DragUpdated):
                DragType newDragType = evt.alt ? DragType.CreateMultiple : DragType.SpriteAnimation;

                if (s_DragType != newDragType || s_SceneDragObjects == null)               // Either this is first time we are here OR evt.alt changed during drag
                {
                    if (!ExistingAssets(objectReferences) && PathsAreValidTextures(paths)) // External drag with images that are not in the project
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                        s_SceneDragObjects     = new List <Object>();
                        s_DragType             = newDragType;
                    }
                    else     // Internal drag with assets from project
                    {
                        List <Sprite> assets = GetSpriteFromPathsOrObjects(objectReferences, paths, evt.type);

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

                        if (s_DragType != DragType.NotInitialized)     // evt.alt changed during drag, so we need to cleanup and start over
                        {
                            CleanUp(true);
                        }

                        s_DragType = newDragType;
                        CreateSceneDragObjects(assets, sceneView);
                        IgnoreForRaycasts(s_SceneDragObjects);
                    }
                }

                PositionSceneDragObjects(s_SceneDragObjects, sceneView, evt.mousePosition);

                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                evt.Use();
                break;

            case (EventType.DragPerform):
                List <Sprite> sprites = GetSpriteFromPathsOrObjects(objectReferences, paths, evt.type);

                if (sprites.Count > 0 && s_SceneDragObjects != null)
                {
                    // Store current undoIndex to undo all operations done if any part of sprite creation fails
                    int undoIndex = Undo.GetCurrentGroup();

                    // For external drags, we have delayed all creation to DragPerform because only now we have the imported sprite assets
                    if (s_SceneDragObjects.Count == 0)
                    {
                        CreateSceneDragObjects(sprites, sceneView);
                        PositionSceneDragObjects(s_SceneDragObjects, sceneView, evt.mousePosition);
                    }

                    foreach (GameObject dragGO in s_SceneDragObjects)
                    {
                        dragGO.hideFlags = HideFlags.None;

                        // When in e.g Prefab Mode ensure to reparent dragged objects under the prefab root
                        if (sceneView.customParentForDraggedObjects != null)
                        {
                            dragGO.transform.SetParent(sceneView.customParentForDraggedObjects, true);
                        }

                        Undo.RegisterCreatedObjectUndo(dragGO, "Create Sprite");
                        EditorUtility.SetDirty(dragGO);
                    }

                    bool createGameObject = true;
                    if (s_DragType == DragType.SpriteAnimation && sprites.Count > 1)
                    {
                        createGameObject = AddAnimationToGO((GameObject)s_SceneDragObjects[0], sprites.ToArray(), saveFileDialog);
                    }

                    if (createGameObject)
                    {
                        Selection.objects = s_SceneDragObjects.ToArray();
                    }
                    else
                    {
                        // Revert all Create Sprite actions if animation failed to be created or was cancelled
                        Undo.RevertAllDownToGroup(undoIndex);
                    }
                    CleanUp(!createGameObject);
                    evt.Use();
                }
                break;

            case EventType.DragExited:
                if (s_SceneDragObjects != null)
                {
                    CleanUp(true);
                    evt.Use();
                }
                break;
            }
        }
Ejemplo n.º 8
0
        internal static void RemoveTerrainLayer(Terrain terrain, int index)
        {
            var terrainData = terrain.terrainData;
            int width       = terrainData.alphamapWidth;
            int height      = terrainData.alphamapHeight;

            float[,,] alphamap = terrainData.GetAlphamaps(0, 0, width, height);
            int alphaCount = alphamap.GetLength(2);

            int newAlphaCount = alphaCount - 1;

            float[,,] newalphamap = new float[height, width, newAlphaCount];

            // move further alphamaps one index below
            for (int y = 0; y < height; ++y)
            {
                for (int x = 0; x < width; ++x)
                {
                    for (int a = 0; a < index; ++a)
                    {
                        newalphamap[y, x, a] = alphamap[y, x, a];
                    }
                    for (int a = index + 1; a < alphaCount; ++a)
                    {
                        newalphamap[y, x, a - 1] = alphamap[y, x, a];
                    }
                }
            }

            // normalize weights in new alpha map
            for (int y = 0; y < height; ++y)
            {
                for (int x = 0; x < width; ++x)
                {
                    float sum = 0.0F;
                    for (int a = 0; a < newAlphaCount; ++a)
                    {
                        sum += newalphamap[y, x, a];
                    }
                    if (sum >= 0.01)
                    {
                        float multiplier = 1.0F / sum;
                        for (int a = 0; a < newAlphaCount; ++a)
                        {
                            newalphamap[y, x, a] *= multiplier;
                        }
                    }
                    else
                    {
                        // in case all weights sum to pretty much zero (e.g.
                        // removing splat that had 100% weight), assign
                        // everything to 1st splat texture (just like
                        // initial terrain).
                        for (int a = 0; a < newAlphaCount; ++a)
                        {
                            newalphamap[y, x, a] = (a == 0) ? 1.0f : 0.0f;
                        }
                    }
                }
            }

            // remove splat from terrain prototypes
            var layers    = terrainData.terrainLayers;
            var newSplats = new TerrainLayer[layers.Length - 1];

            for (int a = 0; a < index; ++a)
            {
                newSplats[a] = layers[a];
            }
            for (int a = index + 1; a < alphaCount; ++a)
            {
                newSplats[a - 1] = layers[a];
            }
            Undo.SetCurrentGroupName("Remove terrain layer");
            terrainData.SetTerrainLayersRegisterUndo(newSplats, "Remove Layer");
            var undoObjects = new List <UnityEngine.Object>();

            undoObjects.AddRange(terrainData.alphamapTextures);
            Undo.RegisterCompleteObjectUndo(undoObjects.ToArray(), "Apply Modified Alphamaps");
            Undo.CollapseUndoOperations(Undo.GetCurrentGroup());

            // set new alphamaps
            terrainData.SetAlphamaps(0, 0, newalphamap);
        }
Ejemplo n.º 9
0
        private void HandleEditorDragging(int editorIndex, Rect targetRect, float markerY, bool bottomTarget, ActiveEditorTracker tracker)
        {
            Event     current = Event.current;
            EventType type    = current.type;

            switch (type)
            {
            case EventType.Repaint:
                if (this.m_TargetIndex != -1 && targetRect.Contains(current.mousePosition))
                {
                    Rect position = new Rect(targetRect.x, markerY, targetRect.width, 3f);
                    if (!this.m_TargetAbove)
                    {
                        position.y += 2f;
                    }
                    EditorDragging.Styles.insertionMarker.Draw(position, false, false, false, false);
                }
                return;

            case EventType.Layout:
IL_26:
                if (type != EventType.DragExited)
                {
                    return;
                }
                this.m_TargetIndex = -1;
                return;

            case EventType.DragUpdated:
                if (targetRect.Contains(current.mousePosition))
                {
                    EditorDragging.DraggingMode?draggingMode = DragAndDrop.GetGenericData("InspectorEditorDraggingMode") as EditorDragging.DraggingMode?;
                    if (!draggingMode.HasValue)
                    {
                        UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences;
                        if (objectReferences.Length == 0)
                        {
                            draggingMode = new EditorDragging.DraggingMode?(EditorDragging.DraggingMode.NotApplicable);
                        }
                        else if (objectReferences.All((UnityEngine.Object o) => o is Component && !(o is Transform)))
                        {
                            draggingMode = new EditorDragging.DraggingMode?(EditorDragging.DraggingMode.Component);
                        }
                        else if (objectReferences.All((UnityEngine.Object o) => o is MonoScript))
                        {
                            draggingMode = new EditorDragging.DraggingMode?(EditorDragging.DraggingMode.Script);
                        }
                        else
                        {
                            draggingMode = new EditorDragging.DraggingMode?(EditorDragging.DraggingMode.NotApplicable);
                        }
                        DragAndDrop.SetGenericData("InspectorEditorDraggingMode", draggingMode);
                    }
                    if (draggingMode.Value != EditorDragging.DraggingMode.NotApplicable)
                    {
                        Editor[]             activeEditors     = tracker.activeEditors;
                        UnityEngine.Object[] objectReferences2 = DragAndDrop.objectReferences;
                        if (bottomTarget)
                        {
                            this.m_TargetAbove = false;
                            this.m_TargetIndex = this.m_LastIndex;
                        }
                        else
                        {
                            this.m_TargetAbove = (current.mousePosition.y < targetRect.y + targetRect.height / 2f);
                            this.m_TargetIndex = editorIndex;
                            if (this.m_TargetAbove)
                            {
                                this.m_TargetIndex++;
                                while (this.m_TargetIndex < activeEditors.Length && this.m_InspectorWindow.ShouldCullEditor(activeEditors, this.m_TargetIndex))
                                {
                                    this.m_TargetIndex++;
                                }
                                if (this.m_TargetIndex == activeEditors.Length)
                                {
                                    this.m_TargetIndex = -1;
                                    return;
                                }
                            }
                        }
                        if (this.m_TargetAbove && this.m_InspectorWindow.EditorHasLargeHeader(this.m_TargetIndex, activeEditors))
                        {
                            this.m_TargetIndex--;
                            while (this.m_TargetIndex >= 0 && this.m_InspectorWindow.ShouldCullEditor(activeEditors, this.m_TargetIndex))
                            {
                                this.m_TargetIndex--;
                            }
                            if (this.m_TargetIndex == -1)
                            {
                                return;
                            }
                            this.m_TargetAbove = false;
                        }
                        if (draggingMode.Value == EditorDragging.DraggingMode.Script)
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                        }
                        else
                        {
                            bool flag = false;
                            if (activeEditors[this.m_TargetIndex].targets.All((UnityEngine.Object t) => t is Component))
                            {
                                Component[] targetComponents = activeEditors[this.m_TargetIndex].targets.Cast <Component>().ToArray <Component>();
                                Component[] sourceComponents = DragAndDrop.objectReferences.Cast <Component>().ToArray <Component>();
                                flag = this.MoveOrCopyComponents(sourceComponents, targetComponents, EditorUtility.EventHasDragCopyModifierPressed(current), true);
                            }
                            if (!flag)
                            {
                                DragAndDrop.visualMode = DragAndDropVisualMode.None;
                                this.m_TargetIndex     = -1;
                                return;
                            }
                            DragAndDrop.visualMode = ((!EditorUtility.EventHasDragCopyModifierPressed(current)) ? DragAndDropVisualMode.Move : DragAndDropVisualMode.Copy);
                        }
                        current.Use();
                    }
                }
                else
                {
                    this.m_TargetIndex = -1;
                }
                return;

            case EventType.DragPerform:
                if (this.m_TargetIndex != -1)
                {
                    EditorDragging.DraggingMode?draggingMode2 = DragAndDrop.GetGenericData("InspectorEditorDraggingMode") as EditorDragging.DraggingMode?;
                    if (!draggingMode2.HasValue || draggingMode2.Value == EditorDragging.DraggingMode.NotApplicable)
                    {
                        this.m_TargetIndex = -1;
                    }
                    else
                    {
                        Editor[] activeEditors2 = tracker.activeEditors;
                        if (activeEditors2[this.m_TargetIndex].targets.All((UnityEngine.Object t) => t is Component))
                        {
                            Component[] array = activeEditors2[this.m_TargetIndex].targets.Cast <Component>().ToArray <Component>();
                            if (draggingMode2.Value == EditorDragging.DraggingMode.Script)
                            {
                                IEnumerable <MonoScript> enumerable = DragAndDrop.objectReferences.Cast <MonoScript>();
                                bool        flag2  = true;
                                Component[] array2 = array;
                                for (int i = 0; i < array2.Length; i++)
                                {
                                    Component  targetComponent = array2[i];
                                    GameObject gameObject      = targetComponent.gameObject;
                                    if (enumerable.Any((MonoScript s) => !ComponentUtility.WarnCanAddScriptComponent(targetComponent.gameObject, s)))
                                    {
                                        flag2 = false;
                                        break;
                                    }
                                }
                                if (flag2)
                                {
                                    Undo.IncrementCurrentGroup();
                                    int         currentGroup = Undo.GetCurrentGroup();
                                    int         num          = 0;
                                    Component[] array3       = new Component[array.Length * enumerable.Count <MonoScript>()];
                                    Component[] array4       = array;
                                    for (int j = 0; j < array4.Length; j++)
                                    {
                                        Component  component   = array4[j];
                                        GameObject gameObject2 = component.gameObject;
                                        foreach (MonoScript current2 in enumerable)
                                        {
                                            array3[num++] = Undo.AddComponent(gameObject2, current2.GetClass());
                                        }
                                    }
                                    if (!ComponentUtility.MoveComponentsRelativeToComponents(array3, array, this.m_TargetAbove))
                                    {
                                        Undo.RevertAllDownToGroup(currentGroup);
                                    }
                                }
                            }
                            else
                            {
                                Component[] array5 = DragAndDrop.objectReferences.Cast <Component>().ToArray <Component>();
                                if (array5.Length == 0 || array.Length == 0)
                                {
                                    return;
                                }
                                this.MoveOrCopyComponents(array5, array, EditorUtility.EventHasDragCopyModifierPressed(current), false);
                            }
                            this.m_TargetIndex = -1;
                            DragAndDrop.AcceptDrag();
                            current.Use();
                            GUIUtility.ExitGUI();
                        }
                    }
                }
                return;
            }
            goto IL_26;
        }
Ejemplo n.º 10
0
        internal void Show(UnityEngine.Object obj, Type requiredType, SerializedProperty property, bool allowSceneObjects, List <int> allowedInstanceIDs, Action <UnityEngine.Object> onObjectSelectorClosed, Action <UnityEngine.Object> onObjectSelectedUpdated)
        {
            this.m_ObjectSelectorReceiver  = null;
            this.m_AllowSceneObjects       = allowSceneObjects;
            this.m_IsShowingAssets         = true;
            this.m_AllowedIDs              = allowedInstanceIDs;
            this.m_OnObjectSelectorClosed  = onObjectSelectorClosed;
            this.m_OnObjectSelectorUpdated = onObjectSelectedUpdated;
            if (property != null)
            {
                if (requiredType == null)
                {
                    ScriptAttributeUtility.GetFieldInfoFromProperty(property, out requiredType);
                    if (requiredType == null)
                    {
                        this.m_RequiredType = this.s_MatchPPtrTypeName.Match(property.type).Groups[1].Value;
                    }
                }
                obj = property.objectReferenceValue;
                this.m_ObjectBeingEdited = property.serializedObject.targetObject;
                if (this.m_ObjectBeingEdited != null && EditorUtility.IsPersistent(this.m_ObjectBeingEdited))
                {
                    this.m_AllowSceneObjects = false;
                }
            }
            if (this.m_AllowSceneObjects)
            {
                if (obj != null)
                {
                    if (typeof(Component).IsAssignableFrom(obj.GetType()))
                    {
                        obj = ((Component)obj).gameObject;
                    }
                    this.m_IsShowingAssets = EditorUtility.IsPersistent(obj);
                }
                else
                {
                    this.m_IsShowingAssets = (requiredType != typeof(GameObject) && !typeof(Component).IsAssignableFrom(requiredType));
                }
            }
            else
            {
                this.m_IsShowingAssets = true;
            }
            this.m_DelegateView = GUIView.current;
            if (requiredType != null)
            {
                this.m_RequiredType = ((!typeof(ScriptableObject).IsAssignableFrom(requiredType) && !typeof(MonoBehaviour).IsAssignableFrom(requiredType)) ? requiredType.Name : requiredType.FullName);
            }
            this.m_SearchFilter      = "";
            this.m_OriginalSelection = obj;
            this.m_ModalUndoGroup    = Undo.GetCurrentGroup();
            ContainerWindow.SetFreezeDisplay(true);
            base.ShowWithMode(ShowMode.AuxWindow);
            base.titleContent = EditorGUIUtility.TrTextContent("Select " + ((requiredType != null) ? requiredType.Name : this.m_RequiredType), null, null);
            Rect position = this.m_Parent.window.position;

            position.width  = EditorPrefs.GetFloat("ObjectSelectorWidth", 200f);
            position.height = EditorPrefs.GetFloat("ObjectSelectorHeight", 390f);
            base.position   = position;
            base.minSize    = new Vector2(200f, 335f);
            base.maxSize    = new Vector2(10000f, 10000f);
            this.SetupPreview();
            base.Focus();
            ContainerWindow.SetFreezeDisplay(false);
            this.m_FocusSearchFilter = true;
            this.m_Parent.AddToAuxWindowList();
            int num = (!(obj != null)) ? 0 : obj.GetInstanceID();

            if (property != null && property.hasMultipleDifferentValues)
            {
                num = 0;
            }
            if (ObjectSelector.ShouldTreeViewBeUsed(requiredType))
            {
                this.m_ObjectTreeWithSearch.Init(base.position, this, new UnityAction <ObjectTreeForSelector.TreeSelectorData>(this.CreateAndSetTreeView), new UnityAction <TreeViewItem>(this.TreeViewSelection), new UnityAction(this.ItemWasDoubleClicked), num, 0);
            }
            else
            {
                this.InitIfNeeded();
                this.m_ListArea.InitSelection(new int[]
                {
                    num
                });
                if (num != 0)
                {
                    this.m_ListArea.Frame(num, true, false);
                }
            }
        }