상속: MonoBehaviour
예제 #1
0
    public void ChangesFilterBox(Vector3 mousePos, DragAndDrop.ItemType foodType, DragAndDrop.FilterType filterType, bool saltType)
    {
        if (IsMouseOverBox(mousePos))
        {
            filter = filterType;
            List<DragAndDrop.ItemType> tempFoodType = new List<DragAndDrop.ItemType>();

            GetComponent<SpriteRenderer>().sprite = spriteManagerScript.GetSpriteFilterType(filterType);

            for (int i = 0; i < connection.Length; i++)
            {
                FishTank tempTank = connection[i].GetComponent<FishTank>();
                tempFoodType = tempTank.GetTankFoodType();
                saltType = tempTank.GetTankSalt();

                if(filter == DragAndDrop.FilterType.food)
                {
                    tempFoodType.Clear();
                } else if(filter == DragAndDrop.FilterType.salt)
                {
                    saltType = false;
                }

                tempTank.FlowableObjects(tempFoodType, saltType);
            }

        }
    }
예제 #2
0
 public void SetSaltFilter(DragAndDrop.ItemType saltFilterType)
 {
     if (filter == DragAndDrop.FilterType.salt)
     {
         saltFilterType = DragAndDrop.ItemType.none;
     }
 }
예제 #3
0
 public void SetFoodFilter(DragAndDrop.ItemType foodFilterType)
 {
     if (filter == DragAndDrop.FilterType.food)
     {
         foodFilterType = DragAndDrop.ItemType.none;
     }
 }
예제 #4
0
    public void AddFish(Vector3 mousePos, DragAndDrop.FishType fishType, bool saltType)
    {
        if (IsMouseOverBox(mousePos))
        {
            Transform fishPos = transform.FindChild("FishPosition");
            tankFishType = fishType;

            fishPos.transform.localScale = new Vector3(fishPos.GetComponent<BoxCollider2D>().size.x - fishPos.transform.localScale.x, fishPos.GetComponent<BoxCollider2D>().size.y - fishPos.transform.localScale.y, 1);
            transform.FindChild("FishPosition").GetComponent<SpriteRenderer>().sprite = spriteManagerScript.GetSpriteFishType(fishType);
        }
    }
예제 #5
0
 public GameObject GetFoodGameObject(DragAndDrop.ItemType foodType)
 {
     if(foodType == DragAndDrop.ItemType.red)
     {
         return redFood;
     } else if(foodType == DragAndDrop.ItemType.blue)
     {
         return blueFood;
     }
     return defaultFood;
 }
예제 #6
0
 public GameObject GetFilterGameObject(DragAndDrop.FilterType filterType)
 {
     if(filterType == DragAndDrop.FilterType.food)
     {
         return foodFilterGameObject;
     } else if(filterType == DragAndDrop.FilterType.salt)
     {
         return saltFilterGameObject;
     }
     return defaultFood;
 }
예제 #7
0
    public void ChangesBox(Vector3 mousePos, DragAndDrop.ItemType foodType, DragAndDrop.FilterType filterType, bool saltType)
    {
        if (IsMouseOverBox(mousePos))
        {
            foodTypeSeed.Add(foodType);
            saltTypeSeed = saltType;
            if (foodType != DragAndDrop.ItemType.none)
            {
                if(!tankFoodType.Contains(foodType))
                {
                    tankFoodType.Add(foodType);
                }
            }  else if(saltType)
            {
                tankSalt = saltType;
            }
            FlowableObjects(tankFoodType, tankSalt);

            //else if (fishType != DragAndDrop.ItemType.none)
            //{
            //    tankFishType = fishType;
            //}
        }
    }
예제 #8
0
 public GameObject GetFishGameObject(DragAndDrop.FishType fishType)
 {
     if(fishType.fish == DragAndDrop.ItemType.blue)
     {
         if(fishType.salt)
         {
             return blueSaltWaterFish;
         } else
         {
             return blueFreshWaterFish;
         }
     } else if (fishType.fish == DragAndDrop.ItemType.red)
     {
         if (fishType.salt)
         {
             return redSaltWaterFish;
         }
         else
         {
             return redFreshWaterFish;
         }
     }
     return defaultFood;
 }
예제 #9
0
    /// <summary>
    /// Draw the custom wizard.
    /// </summary>

    void OnGUI()
    {
        Event     currentEvent = Event.current;
        EventType type         = currentEvent.type;

        int x = cellPadding, y = cellPadding;
        int width    = Screen.width - cellPadding;
        int spacingX = cellSize + cellPadding;
        int spacingY = spacingX;

        if (mMode == Mode.DetailedMode)
        {
            spacingY += 32;
        }

        GameObject dragged         = draggedObject;
        bool       isDragging      = (dragged != null);
        int        indexUnderMouse = GetCellUnderMouse(spacingX, spacingY);
        Item       selection       = isDragging ? FindItem(dragged) : null;
        string     searchFilter    = NGUISettings.searchField;

        int newTab = mTab;

        GUILayout.BeginHorizontal();
        if (GUILayout.Toggle(newTab == 0, "1", "ButtonLeft"))
        {
            newTab = 0;
        }
        if (GUILayout.Toggle(newTab == 1, "2", "ButtonMid"))
        {
            newTab = 1;
        }
        if (GUILayout.Toggle(newTab == 2, "3", "ButtonMid"))
        {
            newTab = 2;
        }
        if (GUILayout.Toggle(newTab == 3, "4", "ButtonMid"))
        {
            newTab = 3;
        }
        if (GUILayout.Toggle(newTab == 4, "5", "ButtonRight"))
        {
            newTab = 4;
        }
        GUILayout.EndHorizontal();

        if (mTab != newTab)
        {
            Save();
            mTab   = newTab;
            mReset = true;
            NGUISettings.SetInt("NGUI Prefab Tab", mTab);
            Load();
        }

        if (mReset && type == EventType.Repaint)
        {
            mReset = false;
            foreach (Item item in mItems)
            {
                GeneratePreview(item, null);
            }
            RectivateLights();
        }

        // Search field
        GUILayout.BeginHorizontal();
        {
            string after = EditorGUILayout.TextField("", searchFilter, "SearchTextField", GUILayout.Width(Screen.width - 20f));

            if (GUILayout.Button("", "SearchCancelButton", GUILayout.Width(18f)))
            {
                after = "";
                GUIUtility.keyboardControl = 0;
            }

            if (searchFilter != after)
            {
                NGUISettings.searchField = after;
                searchFilter             = after;
            }
        }
        GUILayout.EndHorizontal();

        bool eligibleToDrag = (currentEvent.mousePosition.y < Screen.height - 40);

        if (type == EventType.MouseDown)
        {
            mMouseIsInside = true;
        }
        else if (type == EventType.MouseDrag)
        {
            mMouseIsInside = true;

            if (indexUnderMouse != -1 && eligibleToDrag)
            {
                // Drag operation begins
                if (draggedObjectIsOurs)
                {
                    DragAndDrop.StartDrag("Prefab Tool");
                }
                currentEvent.Use();
            }
        }
        else if (type == EventType.MouseUp)
        {
            DragAndDrop.PrepareStartDrag();
            mMouseIsInside = false;
            Repaint();
        }
        else if (type == EventType.DragUpdated)
        {
            // Something dragged into the window
            mMouseIsInside = true;
            UpdateVisual();
            currentEvent.Use();
        }
        else if (type == EventType.DragPerform)
        {
            // We've dropped a new object into the window
            if (dragged != null)
            {
                if (selection != null)
                {
                    DestroyTexture(selection);
                    mItems.Remove(selection);
                }

                AddItem(dragged, indexUnderMouse);
                draggedObject = null;
            }
            mMouseIsInside = false;
            currentEvent.Use();
        }
        else if (type == EventType.DragExited || type == EventType.Ignore)
        {
            mMouseIsInside = false;
        }

        // If the mouse is not inside the window, clear the selection and dragged object
        if (!mMouseIsInside)
        {
            selection = null;
            dragged   = null;
        }

        // Create a list of indices, inserting an entry of '-1' underneath the dragged object
        BetterList <int> indices = new BetterList <int>();

        for (int i = 0; i < mItems.size;)
        {
            if (dragged != null && indices.size == indexUnderMouse)
            {
                indices.Add(-1);
            }

            if (mItems[i] != selection)
            {
                if (string.IsNullOrEmpty(searchFilter) ||
                    mItems[i].prefab.name.IndexOf(searchFilter, System.StringComparison.CurrentCultureIgnoreCase) != -1)
                {
                    indices.Add(i);
                }
            }
            ++i;
        }

        // There must always be '-1' (Add/Move slot) present
        if (!indices.Contains(-1))
        {
            indices.Add(-1);
        }

        // We want to start dragging something from within the window
        if (eligibleToDrag && type == EventType.MouseDown && indexUnderMouse > -1)
        {
            GUIUtility.keyboardControl = 0;

            if (currentEvent.button == 0 && indexUnderMouse < indices.size)
            {
                int index = indices[indexUnderMouse];

                if (index != -1 && index < mItems.size)
                {
                    selection     = mItems[index];
                    draggedObject = selection.prefab;
                    dragged       = selection.prefab;
                    currentEvent.Use();
                }
            }
        }
        //else if (type == EventType.MouseUp && currentEvent.button == 1 && indexUnderMouse > mItems.size)
        //{
        //    NGUIContextMenu.AddItem("Reset", false, RemoveItem, index);
        //    NGUIContextMenu.Show();
        //}

        // Draw the scroll view with prefabs
        mPos = GUILayout.BeginScrollView(mPos);
        {
            Color normal = new Color(1f, 1f, 1f, 0.5f);

            for (int i = 0; i < indices.size; ++i)
            {
                int  index = indices[i];
                Item ent   = (index != -1) ? mItems[index] : selection;

                if (ent != null && ent.prefab == null)
                {
                    mItems.RemoveAt(index);
                    continue;
                }

                Rect rect  = new Rect(x, y, cellSize, cellSize);
                Rect inner = rect;
                inner.xMin += 2f;
                inner.xMax -= 2f;
                inner.yMin += 2f;
                inner.yMax -= 2f;
                rect.yMax  -= 1f;                // Button seems to be mis-shaped. It's height is larger than its width by a single pixel.

                if (!isDragging && (mMode == Mode.CompactMode || (ent == null || ent.tex != null)))
                {
                    mContent.tooltip = (ent != null) ? ent.prefab.name : "Click to add";
                }
                else
                {
                    mContent.tooltip = "";
                }

                //if (ent == selection)
                {
                    GUI.color = normal;
                    NGUIEditorTools.DrawTiledTexture(inner, NGUIEditorTools.backdropTexture);
                }

                GUI.color           = Color.white;
                GUI.backgroundColor = normal;

                if (GUI.Button(rect, mContent, "Button"))
                {
                    if (ent == null || currentEvent.button == 0)
                    {
                        string path = EditorUtility.OpenFilePanel("Add a prefab", NGUISettings.currentPath, "prefab");

                        if (!string.IsNullOrEmpty(path))
                        {
                            NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
                            Item newEnt = CreateItemByPath(path);

                            if (newEnt != null)
                            {
                                mItems.Add(newEnt);
                                Save();
                            }
                        }
                    }
                    else if (currentEvent.button == 1)
                    {
                        NGUIContextMenu.AddItem("Delete", false, RemoveItem, index);
                        NGUIContextMenu.Show();
                    }
                }

                string caption = (ent == null) ? "" : ent.prefab.name.Replace("Control - ", "");

                if (ent != null)
                {
                    if (ent.tex != null)
                    {
                        GUI.DrawTexture(inner, ent.tex);
                    }
                    else if (mMode != Mode.DetailedMode)
                    {
                        GUI.Label(inner, caption, mStyle);
                        caption = "";
                    }
                }
                else
                {
                    GUI.Label(inner, "Add", mStyle);
                }

                if (mMode == Mode.DetailedMode)
                {
                    GUI.backgroundColor = new Color(1f, 1f, 1f, 0.5f);
                    GUI.contentColor    = new Color(1f, 1f, 1f, 0.7f);
                    GUI.Label(new Rect(rect.x, rect.y + rect.height, rect.width, 32f), caption, "ProgressBarBack");
                    GUI.contentColor    = Color.white;
                    GUI.backgroundColor = Color.white;
                }

                x += spacingX;

                if (x + spacingX > width)
                {
                    y += spacingY;
                    x  = cellPadding;
                }
            }
            GUILayout.Space(y);
        }
        GUILayout.EndScrollView();

        // Mode
        Mode modeAfter = (Mode)EditorGUILayout.EnumPopup(mMode);

        if (modeAfter != mMode)
        {
            mMode  = modeAfter;
            mReset = true;
            NGUISettings.SetEnum("NGUI Prefab Mode", mMode);
        }
    }
        private void DrawPreComponents()
        {
            if (nodeInfo.GetPrefab() == null)
            {
                return;
            }

            using (var hor = new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();
                if (GUILayout.Button(new GUIContent("←", "快速解析"), EditorStyles.toolbarButton, GUILayout.Width(20)))
                {
                    GenCodeUtil.ChoiseAnUserMonobehiver(nodeInfo.GetPrefab(), component =>
                    {
                        if (component == null)
                        {
                            EditorApplication.Beep();
                        }
                        else
                        {
                            //从旧的脚本解析出
                            GenCodeUtil.AnalysisComponent(component, components);
                        }
                    });
                }
            }

            using (var hor = new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("BaseType:", GUILayout.Width(lableWidth));
                rule.baseTypeIndex = EditorGUILayout.Popup(rule.baseTypeIndex, GenCodeUtil.supportBaseTypes);
                if (GUILayout.Button(new GUIContent("update", "更新脚本控件信息"), EditorStyles.miniButton, GUILayout.Width(60)))
                {
                    var go = nodeInfo.GetPrefab();
                    GenCodeUtil.UpdateScripts(go, components, rule);
                }
            }

            if (preComponentList != null)
            {
                preComponentList.DoLayoutList();
            }

            var addRect = GUILayoutUtility.GetRect(BridgeUI.Drawer.BridgeEditorUtility.currentViewWidth, EditorGUIUtility.singleLineHeight);

            if (addRect.Contains(Event.current.mousePosition))
            {
                if (Event.current.type == EventType.DragUpdated)
                {
                    if (DragAndDrop.objectReferences.Length > 0)
                    {
                        foreach (var item in DragAndDrop.objectReferences)
                        {
                            if (item is GameObject)
                            {
                                DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                            }
                        }
                    }
                }
                else if (Event.current.type == EventType.DragPerform)
                {
                    if (DragAndDrop.objectReferences.Length > 0)
                    {
                        foreach (var item in DragAndDrop.objectReferences)
                        {
                            if (item is GameObject)
                            {
                                var obj    = item as GameObject;
                                var parent = PrefabUtility.GetPrefabParent(obj);
                                if (parent)
                                {
                                    obj = parent as GameObject;
                                }
                                var c_item = new ComponentItem(obj);
                                c_item.components = GenCodeUtil.SortComponent(obj);
                                components.Add(c_item);
                            }
                            else if (item is ScriptableObject)
                            {
                                var c_item = new ComponentItem(item as ScriptableObject);
                                components.Add(c_item);
                            }
                        }
                        DragAndDrop.AcceptDrag();
                    }
                }
            }
        }
예제 #11
0
        public void Draw() {
            if (skin == null) {
                skin = Resources.Load("GUISkins/editorSkin", typeof(GUISkin)) as GUISkin;
            }

            var allRect = EditorGUILayout.BeginVertical();

            bool toggleColor = false;
            Color baseColor = GUI.color;

            GUILayout.Label(label);
            position = EditorGUILayout.BeginScrollView(
                position, false, true, GUILayout.Height(height));

            float y = 0;

            foreach (var item in items) {
                var itemRect = EditorGUILayout.BeginHorizontal();

                if (scrollToItem == item && Event.current.type == EventType.Repaint) {
                    if (y - position.y < 0) { // item above
                        position.y = y;
                    } else if (y - position.y + itemRect.height + 2 >= allRect.height) { // item below ( + 2 - hack)
                        position.y = y - (allRect.height - itemRect.height * 2);
                    }

                    scrollToItem = null;
                }

                if (selectionEnabled) {
                    if (Event.current.type == EventType.MouseDown && Event.current.button == 0) {
                        if (itemRect.Contains(Event.current.mousePosition)) {
                            if (Event.current.shift) {
                                SelectRange(selectedItem, item);
                            } else {
                                selectedItem = item;

                                var currentClickTime = GetTimeMillis();

                                if (currentClickTime - lastClickTime <= 250 && lastClickedItem == selectedItem) {
                                    if (doubleClickCallback != null) {
                                        doubleClickCallback(lastClickedItem);
                                    }
                                    lastClickTime = 0;
                                    lastClickedItem = null;
                                } else {
                                    lastClickTime = currentClickTime;
                                    lastClickedItem = selectedItem;
                                }
                            }
                            
                        }
                    }
                }

                // component value based on skin
                float c = EditorGUIUtility.isProSkin ? 0 : 1;

                GUI.color = toggleColor ? Color.clear : new Color(c, c, c, 0.2f);
                toggleColor = !toggleColor;
                if (item.selected) {
                    GUI.color = toggleColor ? new Color(c, c, c, 0.4f) : new Color(c, c, c, 0.6f);
                }

                GUI.Box(itemRect, "", skin.box);
                GUI.color = baseColor;

                EditorGUILayout.BeginVertical();
                item.OnGUI();
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();

                y += itemRect.height;
            }

            if (items.Count == 0) {
                GUILayout.Label(emptyListMessage);
            }

            GUILayout.FlexibleSpace();

            if (spaceAfter != 0) {
                GUILayout.Space(spaceAfter);
            }

            EditorGUILayout.EndScrollView();

            GUI.color = baseColor;

            EditorGUILayout.EndVertical();

            Event evt = Event.current;
            switch (evt.type) {
                case EventType.MouseDrag:
                case EventType.DragUpdated:
                case EventType.DragPerform:
                    if (!allRect.Contains(evt.mousePosition)) {
                        break;
                    }

                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                    if (evt.type == EventType.DragPerform) {
                        DragAndDrop.AcceptDrag();

                        foreach (Object draggedObject in DragAndDrop.objectReferences) {
                            if (acceptDropTypes.Contains(draggedObject.GetType())) {
                                AcceptDrag(items.Count, draggedObject);
                            }
                        }
                    }
                    break;
            }
        }
//----------------------------------------------------------------------------------------------------------------------

        internal static string ShowFolderSelectorGUI(string label,
                                                     string dialogTitle,
                                                     string fieldValue,
                                                     Func <string, string> onValidFolderSelected)
        {
            string newDirPath = null;

            using (new EditorGUILayout.HorizontalScope()) {
                if (!string.IsNullOrEmpty(label))
                {
                    EditorGUILayout.PrefixLabel(label);
                }

                EditorGUILayout.SelectableLabel(fieldValue,
                                                EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight)
                                                );

                //Drag drop
                Rect folderRect = GUILayoutUtility.GetLastRect();

                Event evt = Event.current;
                switch (evt.type)
                {
                case EventType.DragUpdated:
                case EventType.DragPerform:
                    if (!folderRect.Contains(evt.mousePosition))
                    {
                        return(fieldValue);
                    }

                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    if (evt.type == EventType.DragPerform)
                    {
                        DragAndDrop.AcceptDrag();

                        if (DragAndDrop.paths.Length <= 0)
                        {
                            break;
                        }
                        fieldValue = DragAndDrop.paths[0];
//                            onDragAndDrop(DragAndDrop.paths[0]);
                    }

                    break;

                default:
                    break;
                }


                newDirPath = InspectorUtility.ShowSelectFolderButton(dialogTitle, fieldValue, onValidFolderSelected);

                if (GUILayout.Button("Show", GUILayout.Width(50f), GUILayout.Height(EditorGUIUtility.singleLineHeight)))
                {
                    EditorUtility.RevealInFinder(newDirPath);
                }
            }

            using (new EditorGUILayout.HorizontalScope()) {
                GUILayout.FlexibleSpace();
                EditorGUI.BeginDisabledGroup(!AssetDatabase.IsValidFolder(newDirPath));
                if (GUILayout.Button("Highlight in Project Window", GUILayout.Width(180f)))
                {
                    AssetEditorUtility.PingAssetByPath(newDirPath);
                }
                EditorGUI.EndDisabledGroup();
            }

            return(newDirPath);
        }
        private void DrawAnchoredPanelsPreview(Rect rect, PanelCanvas.AnchoredPanelProperties props)
        {
            bool shouldDrawSelf = leaveFreeSpace.boolValue || props != settings.InitialPanelsAnchored || props.subPanels == null || props.subPanels.Count == 0;

            if (props.subPanels != null && props.subPanels.Count > 0)
            {
                int horizontal = 1, vertical = 1;
                for (int i = 0; i < props.subPanels.Count; i++)
                {
                    PanelDirection anchorDirection = props.subPanels[i].anchorDirection;
                    if (anchorDirection == PanelDirection.Left || anchorDirection == PanelDirection.Right)
                    {
                        horizontal++;
                    }
                    else
                    {
                        vertical++;
                    }
                }

                if (!shouldDrawSelf)
                {
                    PanelDirection anchorDirection = props.subPanels[props.subPanels.Count - 1].anchorDirection;
                    if (anchorDirection == PanelDirection.Left || anchorDirection == PanelDirection.Right)
                    {
                        if (horizontal > 1)
                        {
                            horizontal--;
                        }
                    }
                    else
                    {
                        if (vertical > 1)
                        {
                            vertical--;
                        }
                    }
                }

                float perWidth  = rect.width / horizontal;
                float perHeight = rect.height / vertical;
                for (int i = 0; i < props.subPanels.Count; i++)
                {
                    Rect           subRect         = new Rect(rect);
                    PanelDirection anchorDirection = props.subPanels[i].anchorDirection;
                    if (anchorDirection == PanelDirection.Left)
                    {
                        rect.x       += perWidth;
                        rect.width   -= perWidth;
                        subRect.width = perWidth;
                    }
                    else if (anchorDirection == PanelDirection.Top)
                    {
                        rect.y        += perHeight;
                        rect.height   -= perHeight;
                        subRect.height = perHeight;
                    }
                    else if (anchorDirection == PanelDirection.Right)
                    {
                        rect.width   -= perWidth;
                        subRect.width = perWidth;
                        subRect.x     = rect.xMax;
                    }
                    else
                    {
                        rect.height   -= perHeight;
                        subRect.height = perHeight;
                        subRect.y      = rect.yMax;
                    }

                    DrawAnchoredPanelsPreview(subRect, props.subPanels[i]);
                }
            }

            if (!shouldDrawSelf)
            {
                return;
            }

            string label;

            if (props == settings.InitialPanelsAnchored)
            {
                label = "Free space";
            }
            else
            {
                label = "Panel";

                List <PanelCanvas.PanelTabProperties> tabs = props.panel.tabs;
                for (int i = 0; i < tabs.Count; i++)
                {
                    if (!string.IsNullOrEmpty(tabs[i].tabLabel))
                    {
                        label = tabs[i].tabLabel;
                        break;
                    }
                }

                if (tabs.Count == 1)
                {
                    label = string.Concat(label, "\n1 tab");
                }
                else
                {
                    label = string.Concat(label, "\n", tabs.Count.ToString(), " tabs");
                }
            }

            if (selectedAnchoredPanel == props)
            {
                Color guiColor = GUI.color;
                GUI.color = Color.cyan;
                GUI.Box(rect, label, anchoredPanelGUIStyle);
                GUI.color = guiColor;
            }
            else
            {
                GUI.Box(rect, label, anchoredPanelGUIStyle);
            }

            int controlID = GUIUtility.GetControlID(FocusType.Passive);

            Event ev = Event.current;

            switch (ev.GetTypeForControl(controlID))
            {
            case EventType.MouseDown:
                if (rect.Contains(ev.mousePosition) && ev.button == 0)
                {
                    GUIUtility.hotControl    = controlID;
                    justClickedAnchoredPanel = props;
                }

                break;

            case EventType.MouseDrag:
                if (GUIUtility.hotControl == controlID && props != settings.InitialPanelsAnchored)
                {
                    GUIUtility.hotControl = 0;

                    // Credit: https://forum.unity.com/threads/editor-draganddrop-bug-system-needs-to-be-initialized-by-unity.219342/#post-1464056
                    DragAndDrop.PrepareStartDrag();
                    DragAndDrop.objectReferences = new Object[] { null };
                    DragAndDrop.SetGenericData("props", props);
                    DragAndDrop.StartDrag("AnchoredPanelProperties");

                    ev.Use();
                }

                break;

            case EventType.MouseUp:
                if (GUIUtility.hotControl == controlID)
                {
                    GUIUtility.hotControl = 0;
                }

                break;

            case EventType.DragPerform:
            case EventType.DragUpdated:
                if (props != settings.InitialPanelsAnchored && rect.Contains(ev.mousePosition))
                {
                    PanelCanvas.AnchoredPanelProperties drag = DragAndDrop.GetGenericData("props") as PanelCanvas.AnchoredPanelProperties;
                    if (drag == null)
                    {
                        int      i;
                        Object[] draggedObjects = DragAndDrop.objectReferences;
                        for (i = 0; i < draggedObjects.Length; i++)
                        {
                            if (draggedObjects[i] is GameObject || draggedObjects[i] is Component)
                            {
                                break;
                            }
                        }

                        if (i == draggedObjects.Length)
                        {
                            break;
                        }
                    }

                    DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                    if (ev.type == EventType.DragPerform)
                    {
                        DragAndDrop.AcceptDrag();

                        if (drag != null)
                        {
                            Undo.IncrementCurrentGroup();
                            Undo.RecordObject((PanelCanvas)target, "Swap Tabs");

                            PanelCanvas.PanelProperties temp = props.panel;
                            props.panel = drag.panel;
                            drag.panel  = temp;
                        }
                        else
                        {
                            Undo.IncrementCurrentGroup();
                            Undo.RecordObject((PanelCanvas)target, "Add Tabs");

                            Object[] draggedObjects = DragAndDrop.objectReferences;
                            for (int i = 0; i < draggedObjects.Length; i++)
                            {
                                RectTransform transform;
                                if (draggedObjects[i] is GameObject)
                                {
                                    transform = ((GameObject)draggedObjects[i]).transform as RectTransform;
                                }
                                else
                                {
                                    transform = ((Component)draggedObjects[i]).transform as RectTransform;
                                }

                                if (transform != null)
                                {
                                    if (props.panel.tabs.Find((tab) => tab.content == transform) == null)
                                    {
                                        props.panel.tabs.Add(new PanelCanvas.PanelTabProperties()
                                        {
                                            content = transform
                                        });
                                    }
                                }
                            }
                        }
                    }

                    ev.Use();
                }

                break;
            }

            if (ev.isMouse && GUIUtility.hotControl == controlID)
            {
                ev.Use();
            }
        }
예제 #14
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            Texture browseIcon = EditorGUIUtility.Load("FMOD/SearchIconBlack.png") as Texture;
            Texture openIcon   = EditorGUIUtility.Load("FMOD/StudioIcon.png") as Texture;

            EditorGUI.BeginProperty(position, label, property);
            SerializedProperty pathProperty = property;

            Event e = Event.current;

            if (e.type == EventType.dragPerform && position.Contains(e.mousePosition))
            {
                if (DragAndDrop.objectReferences.Length > 0 &&
                    DragAndDrop.objectReferences[0] != null &&
                    DragAndDrop.objectReferences[0].GetType() == typeof(EditorEventRef))
                {
                    pathProperty.stringValue = ((EditorEventRef)DragAndDrop.objectReferences[0]).Path;
                    GUI.changed = true;
                    e.Use();
                }
            }
            if (e.type == EventType.DragUpdated && position.Contains(e.mousePosition))
            {
                if (DragAndDrop.objectReferences.Length > 0 &&
                    DragAndDrop.objectReferences[0] != null &&
                    DragAndDrop.objectReferences[0].GetType() == typeof(EditorEventRef))
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                    DragAndDrop.AcceptDrag();
                    e.Use();
                }
            }

            float baseHeight = GUI.skin.textField.CalcSize(new GUIContent()).y;

            position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);

            GUIStyle buttonStyle = new GUIStyle(GUI.skin.button);

            buttonStyle.padding.top    = 1;
            buttonStyle.padding.bottom = 1;

            Rect openRect   = new Rect(position.x + position.width - openIcon.width - 15, position.y, openIcon.width + 10, baseHeight);
            Rect searchRect = new Rect(openRect.x - browseIcon.width - 15, position.y, browseIcon.width + 10, baseHeight);
            Rect pathRect   = new Rect(position.x, position.y, searchRect.x - position.x - 5, baseHeight);

            EditorGUI.PropertyField(pathRect, pathProperty, GUIContent.none);
            if (GUI.Button(searchRect, new GUIContent(browseIcon, "Search"), buttonStyle))
            {
                var eventBrowser = EventBrowser.CreateInstance <EventBrowser>();

                #if UNITY_4_6
                eventBrowser.title = "Select FMOD Event";
                #else
                eventBrowser.titleContent = new GUIContent("Select FMOD Event");
                #endif

                eventBrowser.SelectEvent(property);
                eventBrowser.ShowUtility();
            }
            if (GUI.Button(openRect, new GUIContent(openIcon, "Open In FMOD Studio"), buttonStyle) &&
                !String.IsNullOrEmpty(pathProperty.stringValue) &&
                EventManager.EventFromPath(pathProperty.stringValue) != null
                )
            {
                EditorEventRef eventRef = EventManager.EventFromPath(pathProperty.stringValue);
                string         cmd      = string.Format("studio.window.navigateTo(studio.project.lookup(\"{0}\"))", eventRef.Guid.ToString("b"));
                EditorUtils.SendScriptCommand(cmd);
            }

            if (!String.IsNullOrEmpty(pathProperty.stringValue) && EventManager.EventFromPath(pathProperty.stringValue) != null)
            {
                Rect foldoutRect = new Rect(position.x + 10, position.y + baseHeight, position.width, baseHeight);
                property.isExpanded = EditorGUI.Foldout(foldoutRect, property.isExpanded, "Event Properties");
                if (property.isExpanded)
                {
                    var style = new GUIStyle(GUI.skin.label);
                    style.richText = true;
                    EditorEventRef eventRef  = EventManager.EventFromPath(pathProperty.stringValue);
                    float          width     = style.CalcSize(new GUIContent("<b>Oneshot</b>")).x;
                    Rect           labelRect = new Rect(position.x, position.y + baseHeight * 2, width, baseHeight);
                    Rect           valueRect = new Rect(position.x + width + 10, position.y + baseHeight * 2, pathRect.width, baseHeight);

                    GUI.Label(labelRect, new GUIContent("<b>GUID</b>"), style);
                    EditorGUI.SelectableLabel(valueRect, eventRef.Guid.ToString("b"));
                    labelRect.y += baseHeight;
                    valueRect.y += baseHeight;

                    GUI.Label(labelRect, new GUIContent("<b>Banks</b>"), style);
                    StringBuilder builder = new StringBuilder();
                    eventRef.Banks.ForEach((x) => { builder.Append(Path.GetFileNameWithoutExtension(x.Path)); builder.Append(", "); });
                    GUI.Label(valueRect, builder.ToString(0, builder.Length - 2));
                    labelRect.y += baseHeight;
                    valueRect.y += baseHeight;

                    GUI.Label(labelRect, new GUIContent("<b>Panning</b>"), style);
                    GUI.Label(valueRect, eventRef.Is3D ? "3D" : "2D");
                    labelRect.y += baseHeight;
                    valueRect.y += baseHeight;

                    GUI.Label(labelRect, new GUIContent("<b>Stream</b>"), style);
                    GUI.Label(valueRect, eventRef.IsStream.ToString());
                    labelRect.y += baseHeight;
                    valueRect.y += baseHeight;

                    GUI.Label(labelRect, new GUIContent("<b>Oneshot</b>"), style);
                    GUI.Label(valueRect, eventRef.IsOneShot.ToString());
                    labelRect.y += baseHeight;
                    valueRect.y += baseHeight;
                }
            }
            else
            {
                Rect labelRect = new Rect(position.x, position.y + baseHeight, position.width, baseHeight);
                GUI.Label(labelRect, new GUIContent("Event Not Found", EditorGUIUtility.Load("FMOD/NotFound.png") as Texture2D));
            }

            EditorGUI.EndProperty();
        }
예제 #15
0
            public bool DoLayoutProperty(SerializedProperty property)
            {
                if (propIndex.ContainsKey(property.propertyPath) == false)
                {
                    return(false);
                }

                // Draw the header
                string headerText = string.Format("{0} [{1}]", property.displayName, property.arraySize);

                EditorGUILayout.PropertyField(property, new GUIContent(headerText), false);

                // Save header rect for handling drag and drop
                Rect dropRect = GUILayoutUtility.GetLastRect();

                // Draw the reorderable list for the property
                if (property.isExpanded)
                {
                    int newArraySize = EditorGUILayout.IntField("Size", property.arraySize);
                    if (newArraySize != property.arraySize)
                    {
                        property.arraySize = newArraySize;
                    }
                    propIndex[property.propertyPath].DoLayoutList();
                }

                // Handle drag and drop into the header
                Event evt = Event.current;

                if (evt == null)
                {
                    return(true);
                }

                if (evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform)
                {
                    if (dropRect.Contains(evt.mousePosition) == false)
                    {
                        return(true);
                    }

                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    if (evt.type == EventType.DragPerform)
                    {
                        DragAndDrop.AcceptDrag();
                        Action <SerializedProperty, Object[]> handler = null;
                        if (propDropHandlers.TryGetValue(property.propertyPath, out handler))
                        {
                            if (handler != null)
                            {
                                handler(property, DragAndDrop.objectReferences);
                            }
                        }
                        else
                        {
                            foreach (Object dragged_object in DragAndDrop.objectReferences)
                            {
                                if (dragged_object.GetType() != property.GetType())
                                {
                                    continue;
                                }

                                int newIndex = property.arraySize;
                                property.arraySize++;

                                SerializedProperty target = property.GetArrayElementAtIndex(newIndex);
                                target.objectReferenceInstanceIDValue = dragged_object.GetInstanceID();
                            }
                        }
                        evt.Use();
                    }
                }
                return(true);
            }
예제 #16
0
        /// <summary>
        /// Drag-and-Drop Area to catch objects of specific type
        /// </summary>
        /// <typeparam name="T">Asset type to catch</typeparam>
        /// <param name="areaText">Label to display</param>
        /// <param name="height">Height of the Drop Area</param>
        /// <param name="allowExternal">Allow to drag external files and import as unity assets</param>
        /// <param name="externalImportFolder">Path relative to Assets folder</param>
        /// <returns>Received objects. Null if none received</returns>
        public static T[] DropArea <T>(string areaText, float height, bool allowExternal = false,
                                       string externalImportFolder = null) where T : Object
        {
            Event currentEvent = Event.current;
            Rect  dropArea     = GUILayoutUtility.GetRect(0.0f, height, GUILayout.ExpandWidth(true));
            var   style        = new GUIStyle(GUI.skin.box);

            style.alignment = TextAnchor.MiddleCenter;
            GUI.Box(dropArea, areaText, style);

            bool dragEvent = currentEvent.type == EventType.DragUpdated || currentEvent.type == EventType.DragPerform;

            if (!dragEvent)
            {
                return(null);
            }
            bool overDropArea = dropArea.Contains(currentEvent.mousePosition);

            if (!overDropArea)
            {
                return(null);
            }

            DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
            if (currentEvent.type != EventType.DragPerform)
            {
                return(null);
            }

            DragAndDrop.AcceptDrag();
            Event.current.Use();

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

            bool anyExternal = DragAndDrop.paths.Length > 0 &&
                               DragAndDrop.paths.Length > DragAndDrop.objectReferences.Length;

            if (allowExternal && anyExternal)
            {
                var folderToLoad = "/";
                if (!string.IsNullOrEmpty(externalImportFolder))
                {
                    folderToLoad = "/" + externalImportFolder.Replace("Assets/", "").Trim('/', '\\') + "/";
                }

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

                foreach (string externalPath in DragAndDrop.paths)
                {
                    if (externalPath.Length == 0)
                    {
                        continue;
                    }
                    try
                    {
                        var filename     = Path.GetFileName(externalPath);
                        var relativePath = folderToLoad + filename;
                        Directory.CreateDirectory(Application.persistentDataPath + folderToLoad);
                        FileUtil.CopyFileOrDirectory(externalPath, Application.persistentDataPath + relativePath);
                        importedFiles.Add("Assets" + relativePath);
                    }
                    catch (Exception ex)
                    {
                        Debug.LogException(ex);
                    }
                }

                AssetDatabase.Refresh();

                foreach (var importedFile in importedFiles)
                {
                    var asset = AssetDatabase.LoadAssetAtPath <T>(importedFile);
                    if (asset != null)
                    {
                        result.Add(asset);
                        Debug.Log("Asset imported at path: " + importedFile);
                    }
                    else
                    {
                        AssetDatabase.DeleteAsset(importedFile);
                    }
                }
            }
            else
            {
                foreach (Object dragged in DragAndDrop.objectReferences)
                {
                    var validObject = dragged as T ?? AssetDatabase.LoadAssetAtPath <T>(AssetDatabase.GetAssetPath(dragged));

                    if (validObject != null)
                    {
                        result.Add(validObject);
                    }
                }
            }

            return(result.Count > 0 ? result.OrderBy(o => o.name).ToArray() : null);
        }
예제 #17
0
    private void DragAndDropGUI()
    {
        Event evt = Event.current;

        Rect dropArea = new Rect(m_inspectorStartRegion.x, m_inspectorStartRegion.y, m_inspectorEndRegion.width, m_inspectorEndRegion.y - m_inspectorStartRegion.y);

        switch (evt.type)
        {
        case EventType.DragUpdated:
        case EventType.DragPerform:
            if (!dropArea.Contains(evt.mousePosition))
            {
                break;
            }

            DragAndDrop.visualMode = DragAndDropVisualMode.Generic;

            if (evt.type == EventType.DragPerform)
            {
                DragAndDrop.AcceptDrag();

                // Do something
                Material currentMaterial = target as Material;

                Material newMaterial = DragAndDrop.objectReferences[0] as Material;
                //Debug.Log("Drag-n-Drop Material is " + newMaterial + ". Target Material is " + currentMaterial); // + ".  Canvas Material is " + m_uiRenderer.GetMaterial()  );

                // Check to make sure we have a valid material and that the font atlases match.
                if (!newMaterial || newMaterial == currentMaterial || newMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() != currentMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
                {
                    if (newMaterial && newMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() != currentMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
                    {
                        Debug.LogWarning("Drag-n-Drop Material [" + newMaterial.name + "]'s Atlas does not match the Atlas of the currently assigned Font Asset's Atlas.");
                    }
                    break;
                }

                // Check if this material is assigned to an object and active.
                GameObject go = Selection.activeGameObject;
                if (go != null && !go.activeInHierarchy)
                {
                    if (go.GetComponent <TextMeshPro>() != null)
                    {
                        Undo.RecordObject(go.GetComponent <TextMeshPro>(), "Material Assignment");
                        go.GetComponent <TextMeshPro>().fontSharedMaterial = newMaterial;
                    }

#if UNITY_4_6 || UNITY_5
                    if (go.GetComponent <TextMeshProUGUI>() != null)
                    {
                        Undo.RecordObject(go.GetComponent <TextMeshProUGUI>(), "Material Assignment");
                        go.GetComponent <TextMeshProUGUI>().fontSharedMaterial = newMaterial;
                    }
#endif
                }

                TMPro_EventManager.ON_DRAG_AND_DROP_MATERIAL_CHANGED(go, currentMaterial, newMaterial);
                //SceneView.RepaintAll();
                EditorUtility.SetDirty(go);
            }

            evt.Use();
            break;
        }
    }
예제 #18
0
        protected override void RenderEvent(FrameRange viewRange, FrameRange validKeyframeRange)
        {
            if (_animEvtSO == null)
            {
                _animEvtSO   = new SerializedObject(_animEvt);
                _blendLength = _animEvtSO.FindProperty("_blendLength");
                _startOffset = _animEvtSO.FindProperty("_startOffset");
            }


            UpdateEventFromController();

            _animEvtSO.Update();

            FAnimationTrackEditor animTrackEditor = (FAnimationTrackEditor)_trackEditor;

            Rect transitionOffsetRect = _eventRect;

            int startOffsetHandleId = EditorGUIUtility.GetControlID(FocusType.Passive);
            int transitionHandleId  = EditorGUIUtility.GetControlID(FocusType.Passive);

            bool isBlending     = _animEvt.IsBlending();
            bool isAnimEditable = _animEvt.IsAnimationEditable();

            if (isBlending)
            {
                transitionOffsetRect.xMin  = SequenceEditor.GetXForFrame(_animEvt.Start + _animEvt._blendLength) - 3;
                transitionOffsetRect.width = 6;
                transitionOffsetRect.yMin  = transitionOffsetRect.yMax - 8;
            }

            switch (Event.current.type)
            {
            case EventType.MouseDown:
                if (EditorGUIUtility.hotControl == 0 && Event.current.alt && !isAnimEditable)
                {
                    if (isBlending && transitionOffsetRect.Contains(Event.current.mousePosition))
                    {
                        EditorGUIUtility.hotControl = transitionHandleId;

                        if (Selection.activeObject != _transitionToState)
                        {
                            Selection.activeObject = _transitionToState;
                        }

                        Event.current.Use();
                    }
                    else if (_eventRect.Contains(Event.current.mousePosition))
                    {
                        _mouseDown = SequenceEditor.GetFrameForX(Event.current.mousePosition.x) - _animEvt.Start;

                        EditorGUIUtility.hotControl = startOffsetHandleId;

                        Event.current.Use();
                    }
                }
                break;

            case EventType.MouseUp:
                if (EditorGUIUtility.hotControl == transitionHandleId ||
                    EditorGUIUtility.hotControl == startOffsetHandleId)
                {
                    EditorGUIUtility.hotControl = 0;
                    Event.current.Use();
                }
                break;

            case EventType.MouseDrag:
                if (EditorGUIUtility.hotControl == transitionHandleId)
                {
                    int mouseDragPos = Mathf.Clamp(SequenceEditor.GetFrameForX(Event.current.mousePosition.x) - _animEvt.Start, 0, _animEvt.Length);

                    if (_blendLength.intValue != mouseDragPos)
                    {
                        _blendLength.intValue = mouseDragPos;

                        FPlayAnimationEvent prevAnimEvt = (FPlayAnimationEvent)animTrackEditor._track.GetEvent(_animEvt.GetId() - 1);

                        if (_transitionDuration != null)
                        {
                            _transitionDuration.floatValue = (_blendLength.intValue / prevAnimEvt._animationClip.frameRate) / prevAnimEvt._animationClip.length;
                        }

                        Undo.RecordObject(this, "Animation Blending");
                    }
                    Event.current.Use();
                }
                else if (EditorGUIUtility.hotControl == startOffsetHandleId)
                {
                    int mouseDragPos = Mathf.Clamp(SequenceEditor.GetFrameForX(Event.current.mousePosition.x) - _animEvt.Start, 0, _animEvt.Length);

                    int delta = _mouseDown - mouseDragPos;

                    _mouseDown = mouseDragPos;

                    _startOffset.intValue = Mathf.Clamp(_startOffset.intValue + delta, 0, _animEvt._animationClip.isLooping ? _animEvt.Length : Mathf.RoundToInt(_animEvt._animationClip.length * _animEvt._animationClip.frameRate) - _animEvt.Length);

                    if (_transitionOffset != null)
                    {
                        _transitionOffset.floatValue = (_startOffset.intValue / _animEvt._animationClip.frameRate) / _animEvt._animationClip.length;
                    }

                    Undo.RecordObject(this, "Animation Offset");

                    Event.current.Use();
                }
                break;
            }

            _animEvtSO.ApplyModifiedProperties();
            if (_transitionSO != null)
            {
                _transitionSO.ApplyModifiedProperties();
            }


            switch (Event.current.type)
            {
            case EventType.DragUpdated:
                if (_eventRect.Contains(Event.current.mousePosition))
                {
                    int numAnimationsDragged = FAnimationEventInspector.NumAnimationsDragAndDrop(_evt.Sequence.FrameRate);
                    DragAndDrop.visualMode = numAnimationsDragged > 0 ? DragAndDropVisualMode.Link : DragAndDropVisualMode.Rejected;
                    Event.current.Use();
                }
                break;

            case EventType.DragPerform:
                if (_eventRect.Contains(Event.current.mousePosition))
                {
                    AnimationClip animationClipDragged = FAnimationEventInspector.GetAnimationClipDragAndDrop(_evt.Sequence.FrameRate);
                    if (animationClipDragged)
                    {
//						animTrackEditor.ClearPreview();

                        int animFrameLength = Mathf.RoundToInt(animationClipDragged.length * animationClipDragged.frameRate);

                        FAnimationEventInspector.SetAnimationClip(_animEvt, animationClipDragged);
                        FUtility.Resize(_animEvt, new FrameRange(_animEvt.Start, _animEvt.Start + animFrameLength));

                        DragAndDrop.AcceptDrag();
                        Event.current.Use();
                    }
                    else
                    {
                        Event.current.Use();
                    }
                }
                break;
            }

            FrameRange currentRange = _evt.FrameRange;

            base.RenderEvent(viewRange, validKeyframeRange);

            if (isAnimEditable && currentRange.Length != _evt.FrameRange.Length)
            {
                FAnimationEventInspector.ScaleAnimationClip(_animEvt._animationClip, _evt.FrameRange);
            }

            if (Event.current.type == EventType.Repaint)
            {
                if (isBlending && !isAnimEditable && viewRange.Contains(_animEvt.Start + _animEvt._blendLength))
                {
                    GUISkin skin = FUtility.GetFluxSkin();

                    GUIStyle transitionOffsetStyle = skin.GetStyle("BlendOffset");

                    Texture2D t = FUtility.GetFluxTexture("EventBlend.png");

                    Rect r = new Rect(_eventRect.xMin, _eventRect.yMin + 1, transitionOffsetRect.center.x - _eventRect.xMin, _eventRect.height - 2);

                    GUI.color = new Color(1f, 1f, 1f, 0.3f);

                    GUI.DrawTexture(r, t);

                    if (Event.current.alt)
                    {
                        GUI.color = Color.white;
                    }

                    transitionOffsetStyle.Draw(transitionOffsetRect, false, false, false, false);
                }

//				GUI.color = Color.red;

                if (EditorGUIUtility.hotControl == transitionHandleId)
                {
                    Rect transitionOffsetTextRect = transitionOffsetRect;
                    transitionOffsetTextRect.y     -= 16;
                    transitionOffsetTextRect.height = 20;
                    transitionOffsetTextRect.width += 50;
                    GUI.Label(transitionOffsetTextRect, _animEvt._blendLength.ToString(), EditorStyles.label);
                }

                if (EditorGUIUtility.hotControl == startOffsetHandleId)
                {
                    Rect startOffsetTextRect = _eventRect;
                    GUI.Label(startOffsetTextRect, _animEvt._startOffset.ToString(), EditorStyles.label);
                }
            }
        }
예제 #19
0
            private static SearchProvider CreateProvider(string type, string label, string filterId, int priority, GetItemsHandler fetchItemsHandler)
            {
                return(new SearchProvider(type, label)
                {
                    priority = priority,
                    filterId = filterId,

                    isEnabledForContextualSearch = () => QuickSearchTool.IsFocusedWindowTypeName("ProjectBrowser"),

                    fetchItems = fetchItemsHandler,

                    fetchKeywords = (context, lastToken, items) =>
                    {
                        if (!lastToken.StartsWith("t:"))
                        {
                            return;
                        }
                        items.AddRange(typeFilter.Select(t => "t:" + t));
                    },

                    fetchDescription = (item, context) =>
                    {
                        if (AssetDatabase.IsValidFolder(item.id))
                        {
                            return item.id;
                        }
                        long fileSize = new FileInfo(item.id).Length;
                        item.description = $"{item.id} ({EditorUtility.FormatBytes(fileSize)})";

                        return item.description;
                    },

                    fetchThumbnail = (item, context) =>
                    {
                        if (item.thumbnail)
                        {
                            return item.thumbnail;
                        }

                        item.thumbnail = Utils.GetAssetThumbnailFromPath(item.id, SearchSettings.fetchPreview && context.totalItemCount < 200);
                        return item.thumbnail;
                    },

                    startDrag = (item, context) =>
                    {
                        var obj = AssetDatabase.LoadAssetAtPath <Object>(item.id);
                        if (obj != null)
                        {
                            DragAndDrop.PrepareStartDrag();
                            DragAndDrop.objectReferences = new[] { obj };
                            DragAndDrop.StartDrag(item.label);
                        }
                    },

                    trackSelection = (item, context) =>
                    {
                        var asset = AssetDatabase.LoadAssetAtPath <Object>(item.id);
                        if (asset != null)
                        {
                            EditorGUIUtility.PingObject(asset);
                        }
                    },

                    subCategories = new List <NameId>()
                });
            }
예제 #20
0
        public SceneObjectsProvider(string providerId, string displayName = null)
            : base(providerId, displayName)
        {
            priority = 50;
            filterId = "h:";

            subCategories = new List <NameId>
            {
                new NameId("fuzzy", "fuzzy"),
                new NameId("limit", $"limit to {k_LimitMatches} matches")
            };

            isEnabledForContextualSearch = () =>
                                           QuickSearchTool.IsFocusedWindowTypeName("SceneView") ||
                                           QuickSearchTool.IsFocusedWindowTypeName("SceneHierarchyWindow");

            EditorApplication.hierarchyChanged += () => componentsById.Clear();

            onEnable = () =>
            {
                //using (new DebugTimer("Building Scene Object Description"))
                {
                    var objects     = new GameObject[0];
                    var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
                    if (prefabStage != null)
                    {
                        objects = SceneModeUtility.GetObjects(new[] { prefabStage.prefabContentsRoot }, true);
                    }
                    else
                    {
                        var goRoots = new List <UnityEngine.Object>();
                        for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCount; ++i)
                        {
                            goRoots.AddRange(UnityEngine.SceneManagement.SceneManager.GetSceneAt(i).GetRootGameObjects());
                        }
                        objects = SceneModeUtility.GetObjects(goRoots.ToArray(), true);
                    }

                    //using (new DebugTimer($"Fetching {gods.Length} Scene Objects Components"))
                    {
                        gods = new GOD[objects.Length];
                        for (int i = 0; i < objects.Length; ++i)
                        {
                            gods[i].gameObject = objects[i];
                            var id = gods[i].gameObject.GetInstanceID();
                            if (!componentsById.TryGetValue(id, out gods[i].name))
                            {
                                if (gods.Length > k_LODDetail2)
                                {
                                    gods[i].name = CleanString(gods[i].gameObject.name);
                                }
                                else if (gods.Length > k_LODDetail1)
                                {
                                    gods[i].name = CleanString(GetTransformPath(gods[i].gameObject.transform));
                                }
                                else
                                {
                                    gods[i].name = BuildComponents(gods[i].gameObject);
                                }
                                componentsById[id] = gods[i].name;
                            }
                        }

                        indexer = new SceneSearchIndexer(SceneManager.GetActiveScene().name, gods);
                        indexer.Build();
                    }
                }
            };

            onDisable = () =>
            {
                indexer = null;
                gods    = new GOD[0];
            };

            fetchItems = (context, items, provider) =>
            {
                if (gods == null)
                {
                    return;
                }

                if (indexer != null && indexer.IsReady())
                {
                    var results = indexer.Search(context.searchQuery).Take(201);
                    items.AddRange(results.Select(r =>
                    {
                        if (r.index < 0 || r.index >= gods.Length)
                        {
                            return(provider.CreateItem("invalid"));
                        }

                        var gameObjectId   = gods[r.index].gameObject.GetInstanceID().ToString();
                        var gameObjectName = gods[r.index].gameObject.name;
                        var itemScore      = r.score - 1000;
                        if (gameObjectName.Equals(context.searchQuery, StringComparison.InvariantCultureIgnoreCase))
                        {
                            itemScore *= 2;
                        }
                        var item = provider.CreateItem(gameObjectId, itemScore, null, null, null, r.index);
                        item.descriptionFormat = SearchItemDescriptionFormat.Ellipsis |
                                                 SearchItemDescriptionFormat.RightToLeft |
                                                 SearchItemDescriptionFormat.Highlight;
                        return(item);
                    }));
                }

                SearchGODs(context, provider, items);
            };

            fetchLabel = (item, context) =>
            {
                if (item.label != null)
                {
                    return(item.label);
                }

                var go = ObjectFromItem(item);
                if (!go)
                {
                    return(item.id);
                }

                var transformPath = GetTransformPath(go.transform);
                var components    = go.GetComponents <Component>();
                if (components.Length > 2 && components[1] && components[components.Length - 1])
                {
                    item.label = $"{transformPath} ({components[1].GetType().Name}..{components[components.Length-1].GetType().Name})";
                }
                else if (components.Length > 1 && components[1])
                {
                    item.label = $"{transformPath} ({components[1].GetType().Name})";
                }
                else
                {
                    item.label = $"{transformPath} ({item.id})";
                }

                long       score   = 1;
                List <int> matches = new List <int>();
                var        sq      = CleanString(context.searchQuery);
                if (FuzzySearch.FuzzyMatch(sq, CleanString(item.label), ref score, matches))
                {
                    item.label = RichTextFormatter.FormatSuggestionTitle(item.label, matches);
                }

                return(item.label);
            };

            fetchDescription = (item, context) =>
            {
                #if QUICKSEARCH_DEBUG
                item.description = gods[(int)item.data].name + " * " + item.score;
                #else
                var go = ObjectFromItem(item);
                item.description = GetHierarchyPath(go);
                #endif
                return(item.description);
            };

            fetchThumbnail = (item, context) =>
            {
                if (item.thumbnail)
                {
                    return(item.thumbnail);
                }

                var obj = ObjectFromItem(item);
                if (obj != null)
                {
                    if (SearchSettings.fetchPreview)
                    {
                        var assetPath = GetHierarchyAssetPath(obj, true);
                        if (!String.IsNullOrEmpty(assetPath))
                        {
                            item.thumbnail = AssetPreview.GetAssetPreview(obj);
                            if (item.thumbnail)
                            {
                                return(item.thumbnail);
                            }
                            item.thumbnail = Utils.GetAssetThumbnailFromPath(assetPath, true);
                            if (item.thumbnail)
                            {
                                return(item.thumbnail);
                            }
                        }
                    }

                    item.thumbnail = PrefabUtility.GetIconForGameObject(obj);
                    if (item.thumbnail)
                    {
                        return(item.thumbnail);
                    }
                    item.thumbnail = EditorGUIUtility.ObjectContent(obj, obj.GetType()).image as Texture2D;
                }

                return(item.thumbnail);
            };

            startDrag = (item, context) =>
            {
                var obj = ObjectFromItem(item);
                if (obj != null)
                {
                    DragAndDrop.PrepareStartDrag();
                    DragAndDrop.objectReferences = new[] { obj };
                    DragAndDrop.StartDrag("Drag scene object");
                }
            };

            trackSelection = (item, context) => PingItem(item);
        }
    // ReSharper disable once FunctionComplexityOverflow
    public override void OnInspectorGUI()
    {
        EditorGUI.indentLevel = 0;
        var isDirty = false;

        _variation = (SoundGroupVariation)target;

        if (MasterAudioInspectorResources.LogoTexture != null)
        {
            DTGUIHelper.ShowHeaderTexture(MasterAudioInspectorResources.LogoTexture);
        }

        var parentGroup = _variation.ParentGroup;

        if (parentGroup == null)
        {
            DTGUIHelper.ShowLargeBarAlert("This file cannot be edited in Project View.");
            return;
        }

        AudioSource previewer;

        EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
        GUI.contentColor = DTGUIHelper.BrightButtonColor;
        if (GUILayout.Button(new GUIContent("Back to Group", "Select Group in Hierarchy"), EditorStyles.toolbarButton, GUILayout.Width(80)))
        {
            Selection.activeObject = _variation.transform.parent.gameObject;
        }
        GUILayout.FlexibleSpace();

        if (Application.isPlaying)
        {
            // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
            if (_variation.IsPlaying && _variation.VarAudio.clip != null)   // wait for Resource files to load
            {
                GUI.color = Color.green;

                var label = "Playing ({0}%)";

                if (AudioUtil.IsAudioPaused(_variation.VarAudio))
                {
                    GUI.color = Color.yellow;
                    label     = "Paused ({0}%)";
                }

                var percentagePlayed = (int)(_variation.VarAudio.time / _variation.VarAudio.clip.length * 100);

                EditorGUILayout.LabelField(string.Format(label, percentagePlayed),
                                           EditorStyles.miniButtonMid, GUILayout.Height(16), GUILayout.Width(240));

                _variation.frames++;
                isDirty = true;

                GUI.color = DTGUIHelper.BrightButtonColor;
                if (_variation.ObjectToFollow != null || _variation.ObjectToTriggerFrom != null)
                {
                    if (GUILayout.Button("Select Caller", EditorStyles.miniButton, GUILayout.Width(80)))
                    {
                        if (_variation.ObjectToFollow != null)
                        {
                            Selection.activeGameObject = _variation.ObjectToFollow.gameObject;
                        }
                        else
                        {
                            Selection.activeGameObject = _variation.ObjectToTriggerFrom.gameObject;
                        }
                    }
                }
            }
            else
            {
                GUI.color = Color.red;
                EditorGUILayout.LabelField("Not playing", EditorStyles.miniButtonMid, GUILayout.Height(16), GUILayout.Width(240));
            }
        }

        GUI.color        = Color.white;
        GUI.contentColor = Color.white;

        _ma = MasterAudio.Instance;
        var maInScene = _ma != null;

        var canPreview = !DTGUIHelper.IsPrefabInProjectView(_variation);

        if (maInScene)
        {
            var buttonPressed = DTGUIHelper.DTFunctionButtons.None;
            if (canPreview)
            {
                buttonPressed = DTGUIHelper.AddVariationButtons();
            }

            switch (buttonPressed)
            {
            case DTGUIHelper.DTFunctionButtons.Play:
                if (Application.isPlaying)
                {
                    MasterAudio.PlaySoundAndForget(_variation.transform.parent.name, 1f, null, 0f, _variation.name);
                }
                else
                {
                    isDirty = true;

                    previewer = MasterAudioInspector.GetPreviewer();

                    var calcVolume = _variation.VarAudio.volume * parentGroup.groupMasterVolume;

                    switch (_variation.audLocation)
                    {
                    case MasterAudio.AudioLocation.ResourceFile:
                        if (previewer != null)
                        {
                            MasterAudioInspector.StopPreviewer();
                            var fileName = AudioResourceOptimizer.GetLocalizedFileName(_variation.useLocalization, _variation.resourceFileName);
                            previewer.PlayOneShot(Resources.Load(fileName) as AudioClip, calcVolume);
                        }
                        break;

                    case MasterAudio.AudioLocation.Clip:
                        if (previewer != null)
                        {
                            _variation.Trans.position = previewer.transform.position;
                        }

                        _variation.VarAudio.PlayOneShot(_variation.VarAudio.clip, calcVolume);
                        break;

                    case MasterAudio.AudioLocation.FileOnInternet:
                        if (!string.IsNullOrEmpty(_variation.internetFileUrl))
                        {
                            Application.OpenURL(_variation.internetFileUrl);
                        }
                        break;
                    }
                }
                break;

            case DTGUIHelper.DTFunctionButtons.Stop:
                if (Application.isPlaying)
                {
                    MasterAudio.StopAllOfSound(_variation.transform.parent.name);
                }
                else
                {
                    if (_variation.audLocation == MasterAudio.AudioLocation.ResourceFile)
                    {
                        MasterAudioInspector.StopPreviewer();
                    }
                    else
                    {
                        _variation.VarAudio.Stop();
                    }
                }
                break;
            }
        }

        EditorGUILayout.EndHorizontal();

        DTGUIHelper.HelpHeader("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/SoundGroupVariations.htm", "https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MasterAudio_API/class_dark_tonic_1_1_master_audio_1_1_sound_group_variation.html");

        if (maInScene && !Application.isPlaying)
        {
            DTGUIHelper.ShowColorWarning(MasterAudio.PreviewText);
        }

        var oldLocation = _variation.audLocation;

        EditorGUILayout.BeginHorizontal();
        if (!Application.isPlaying)
        {
            var newLocation =
                (MasterAudio.AudioLocation)EditorGUILayout.EnumPopup("Audio Origin", _variation.audLocation);

            if (newLocation != oldLocation)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Audio Origin");
                _variation.audLocation = newLocation;
            }
        }
        else
        {
            EditorGUILayout.LabelField("Audio Origin", _variation.audLocation.ToString());
        }
        DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/SoundGroupVariations.htm#AudioOrigin");
        EditorGUILayout.EndHorizontal();

        switch (_variation.audLocation)
        {
        case MasterAudio.AudioLocation.Clip:
            var newClip = (AudioClip)EditorGUILayout.ObjectField("Audio Clip", _variation.VarAudio.clip, typeof(AudioClip), false);

            if (newClip != _variation.VarAudio.clip)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation.VarAudio, "assign Audio Clip");
                _variation.VarAudio.clip = newClip;
            }
            break;

        case MasterAudio.AudioLocation.FileOnInternet:
            if (oldLocation != _variation.audLocation)
            {
                if (_variation.VarAudio.clip != null)
                {
                    Debug.Log("Audio clip removed to prevent unnecessary memory usage on File On Internet Variation.");
                }
                _variation.VarAudio.clip = null;
            }

            if (!Application.isPlaying)
            {
                var newUrl = EditorGUILayout.TextField("Internet File URL", _variation.internetFileUrl);
                if (newUrl != _variation.internetFileUrl)
                {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Internet File URL");
                    _variation.internetFileUrl = newUrl;
                }
            }
            else
            {
                EditorGUILayout.LabelField("Internet File URL", _variation.internetFileUrl);
                switch (_variation.internetFileLoadStatus)
                {
                case MasterAudio.InternetFileLoadStatus.Loading:
                    DTGUIHelper.ShowLargeBarAlert("Attempting to download.");
                    break;

                case MasterAudio.InternetFileLoadStatus.Loaded:
                    DTGUIHelper.ShowColorWarning("Downloaded and ready to play.");
                    break;

                case MasterAudio.InternetFileLoadStatus.Failed:
                    DTGUIHelper.ShowRedError("Failed Download.");
                    break;
                }
            }

            if (string.IsNullOrEmpty(_variation.internetFileUrl))
            {
                DTGUIHelper.ShowLargeBarAlert("You have not specified a URL for the File On Internet. This Variation will not be available to play without one.");
            }
            break;

        case MasterAudio.AudioLocation.ResourceFile:
            if (oldLocation != _variation.audLocation)
            {
                if (_variation.VarAudio.clip != null)
                {
                    Debug.Log("Audio clip removed to prevent unnecessary memory usage on Resource file Variation.");
                }
                _variation.VarAudio.clip = null;
            }

            EditorGUILayout.BeginVertical();
            var anEvent = Event.current;

            GUI.color = DTGUIHelper.DragAreaColor;
            var dragArea = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
            GUI.Box(dragArea, "Drag Resource Audio clip here to use its name!");
            GUI.color = Color.white;

            string newFilename;

            switch (anEvent.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (!dragArea.Contains(anEvent.mousePosition))
                {
                    break;
                }

                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                if (anEvent.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();

                    foreach (var dragged in DragAndDrop.objectReferences)
                    {
                        // ReSharper disable once ExpressionIsAlwaysNull
                        var aClip = dragged as AudioClip;
                        // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                        if (aClip == null)
                        {
                            continue;
                        }

                        // ReSharper disable HeuristicUnreachableCode
                        var useLocalization = false;
                        newFilename = DTGUIHelper.GetResourcePath(aClip, ref useLocalization);
                        if (string.IsNullOrEmpty(newFilename))
                        {
                            newFilename = aClip.name;
                        }

                        AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Resource filename");
                        _variation.resourceFileName = newFilename;
                        _variation.useLocalization  = useLocalization;
                        break;
                        // ReSharper restore HeuristicUnreachableCode
                    }
                }
                Event.current.Use();
                break;
            }
            EditorGUILayout.EndVertical();

            newFilename = EditorGUILayout.TextField("Resource Filename", _variation.resourceFileName);
            if (newFilename != _variation.resourceFileName)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Resource filename");
                _variation.resourceFileName = newFilename;
            }

            EditorGUI.indentLevel = 1;

            var newLocal = EditorGUILayout.Toggle("Use Localized Folder", _variation.useLocalization);
            if (newLocal != _variation.useLocalization)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Localized Folder");
                _variation.useLocalization = newLocal;
            }

            break;
        }

        EditorGUI.indentLevel = 0;
        var newVolume = DTGUIHelper.DisplayVolumeField(_variation.VarAudio.volume, DTGUIHelper.VolumeFieldType.None, MasterAudio.MixerWidthMode.Normal, 0f, true);

        if (newVolume != _variation.VarAudio.volume)
        {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation.VarAudio, "change Volume");
            _variation.VarAudio.volume = newVolume;
        }

        var newPitch = DTGUIHelper.DisplayPitchField(_variation.VarAudio.pitch);

        if (newPitch != _variation.VarAudio.pitch)
        {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation.VarAudio, "change Pitch");
            _variation.VarAudio.pitch = newPitch;
        }

        if (parentGroup.curVariationMode == MasterAudioGroup.VariationMode.LoopedChain)
        {
            DTGUIHelper.ShowLargeBarAlert("Loop Clip is always OFF for Looped Chain Groups");
        }
        else
        {
            var newLoop = EditorGUILayout.Toggle("Loop Clip", _variation.VarAudio.loop);
            if (newLoop != _variation.VarAudio.loop)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation.VarAudio, "toggle Loop");
                _variation.VarAudio.loop = newLoop;
            }
        }

        EditorGUILayout.BeginHorizontal();
        var newWeight = EditorGUILayout.IntSlider("Voices (Weight)", _variation.weight, 0, 100);

        DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/SoundGroupVariations.htm#Voices");
        EditorGUILayout.EndHorizontal();
        if (newWeight != _variation.weight)
        {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Voices (Weight)");
            _variation.weight = newWeight;
        }

        var newFxTailTime = EditorGUILayout.Slider("FX Tail Time", _variation.fxTailTime, 0f, 10f);

        if (newFxTailTime != _variation.fxTailTime)
        {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change FX Tail Time");
            _variation.fxTailTime = newFxTailTime;
        }

        var filterList = new List <string>()
        {
            MasterAudio.NoGroupName,
            "Low Pass",
            "High Pass",
            "Distortion",
            "Chorus",
            "Echo",
            "Reverb"
        };

        EditorGUILayout.BeginHorizontal();

        var newFilterIndex = EditorGUILayout.Popup("Add Filter Effect", 0, filterList.ToArray());

        DTGUIHelper.AddHelpIcon("https://dl.dropboxusercontent.com/u/40293802/DarkTonic/MA_OnlineDocs/FilterFX.htm");
        EditorGUILayout.EndHorizontal();

        switch (newFilterIndex)
        {
        case 1:
            AddFilterComponent(typeof(AudioLowPassFilter));
            break;

        case 2:
            AddFilterComponent(typeof(AudioHighPassFilter));
            break;

        case 3:
            AddFilterComponent(typeof(AudioDistortionFilter));
            break;

        case 4:
            AddFilterComponent(typeof(AudioChorusFilter));
            break;

        case 5:
            AddFilterComponent(typeof(AudioEchoFilter));
            break;

        case 6:
            AddFilterComponent(typeof(AudioReverbFilter));
            break;
        }

        DTGUIHelper.StartGroupHeader();
        var newUseRndPitch = EditorGUILayout.BeginToggleGroup(" Use Random Pitch", _variation.useRandomPitch);

        if (newUseRndPitch != _variation.useRandomPitch)
        {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Random Pitch");
            _variation.useRandomPitch = newUseRndPitch;
        }

        DTGUIHelper.EndGroupHeader();

        if (_variation.useRandomPitch)
        {
            var newMode = (SoundGroupVariation.RandomPitchMode)EditorGUILayout.EnumPopup("Pitch Compute Mode", _variation.randomPitchMode);
            if (newMode != _variation.randomPitchMode)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Pitch Compute Mode");
                _variation.randomPitchMode = newMode;
            }

            var newPitchMin = DTGUIHelper.DisplayPitchField(_variation.randomPitchMin, "Random Pitch Min");
            if (newPitchMin != _variation.randomPitchMin)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Random Pitch Min");
                _variation.randomPitchMin = newPitchMin;
                if (_variation.randomPitchMax <= _variation.randomPitchMin)
                {
                    _variation.randomPitchMax = _variation.randomPitchMin;
                }
            }

            var newPitchMax = DTGUIHelper.DisplayPitchField(_variation.randomPitchMax, "Random Pitch Max");
            if (newPitchMax != _variation.randomPitchMax)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Random Pitch Max");
                _variation.randomPitchMax = newPitchMax;
                if (_variation.randomPitchMin > _variation.randomPitchMax)
                {
                    _variation.randomPitchMin = _variation.randomPitchMax;
                }
            }
        }

        EditorGUILayout.EndToggleGroup();
        DTGUIHelper.AddSpaceForNonU5(2);

        DTGUIHelper.StartGroupHeader();

        var newUseRndVol = EditorGUILayout.BeginToggleGroup(" Use Random Volume", _variation.useRandomVolume);

        if (newUseRndVol != _variation.useRandomVolume)
        {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Random Volume");
            _variation.useRandomVolume = newUseRndVol;
        }

        DTGUIHelper.EndGroupHeader();

        if (_variation.useRandomVolume)
        {
            var newMode = (SoundGroupVariation.RandomVolumeMode)EditorGUILayout.EnumPopup("Volume Compute Mode", _variation.randomVolumeMode);
            if (newMode != _variation.randomVolumeMode)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Volume Compute Mode");
                _variation.randomVolumeMode = newMode;
            }

            var volMin = 0f;
            if (_variation.randomVolumeMode == SoundGroupVariation.RandomVolumeMode.AddToClipVolume)
            {
                volMin = -1f;
            }

            var newVolMin = DTGUIHelper.DisplayVolumeField(_variation.randomVolumeMin, DTGUIHelper.VolumeFieldType.None, MasterAudio.MixerWidthMode.Normal, volMin, true, "Random Volume Min");
            if (newVolMin != _variation.randomVolumeMin)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Random Volume Min");
                _variation.randomVolumeMin = newVolMin;
                if (_variation.randomVolumeMax <= _variation.randomVolumeMin)
                {
                    _variation.randomVolumeMax = _variation.randomVolumeMin;
                }
            }

            var newVolMax = DTGUIHelper.DisplayVolumeField(_variation.randomVolumeMax, DTGUIHelper.VolumeFieldType.None, MasterAudio.MixerWidthMode.Normal, volMin, true, "Random Volume Max");
            if (newVolMax != _variation.randomVolumeMax)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Random Volume Max");
                _variation.randomVolumeMax = newVolMax;
                if (_variation.randomVolumeMin > _variation.randomVolumeMax)
                {
                    _variation.randomVolumeMin = _variation.randomVolumeMax;
                }
            }
        }

        EditorGUILayout.EndToggleGroup();
        DTGUIHelper.AddSpaceForNonU5(2);

        DTGUIHelper.StartGroupHeader();

        var newSilence = EditorGUILayout.BeginToggleGroup(" Use Random Delay", _variation.useIntroSilence);

        if (newSilence != _variation.useIntroSilence)
        {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Random Delay");
            _variation.useIntroSilence = newSilence;
        }
        DTGUIHelper.EndGroupHeader();

        if (_variation.useIntroSilence)
        {
            var newSilenceMin = EditorGUILayout.Slider("Delay Min (sec)", _variation.introSilenceMin, 0f, 100f);
            if (newSilenceMin != _variation.introSilenceMin)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Delay Min (sec)");
                _variation.introSilenceMin = newSilenceMin;
                if (_variation.introSilenceMin > _variation.introSilenceMax)
                {
                    _variation.introSilenceMax = newSilenceMin;
                }
            }

            var newSilenceMax = EditorGUILayout.Slider("Delay Max (sec)", _variation.introSilenceMax, 0f, 100f);
            if (newSilenceMax != _variation.introSilenceMax)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Delay Max (sec)");
                _variation.introSilenceMax = newSilenceMax;
                if (_variation.introSilenceMax < _variation.introSilenceMin)
                {
                    _variation.introSilenceMin = newSilenceMax;
                }
            }
        }

        EditorGUILayout.EndToggleGroup();
        DTGUIHelper.AddSpaceForNonU5(2);

        DTGUIHelper.StartGroupHeader();

        var newStart = EditorGUILayout.BeginToggleGroup(" Use Random Start Position", _variation.useRandomStartTime);

        if (newStart != _variation.useRandomStartTime)
        {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Random Start Position");
            _variation.useRandomStartTime = newStart;
        }
        DTGUIHelper.EndGroupHeader();

        if (_variation.useRandomStartTime)
        {
            var newMin = EditorGUILayout.Slider("Start Min (%)", _variation.randomStartMinPercent, 0f, 100f);
            if (newMin != _variation.randomStartMinPercent)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Start Min (%)");
                _variation.randomStartMinPercent = newMin;
                if (_variation.randomStartMaxPercent <= _variation.randomStartMinPercent)
                {
                    _variation.randomStartMaxPercent = _variation.randomStartMinPercent;
                }
            }

            var newMax = EditorGUILayout.Slider("Start Max (%)", _variation.randomStartMaxPercent, 0f, 100f);
            if (newMax != _variation.randomStartMaxPercent)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Start Max (%)");
                _variation.randomStartMaxPercent = newMax;
                if (_variation.randomStartMinPercent > _variation.randomStartMaxPercent)
                {
                    _variation.randomStartMinPercent = _variation.randomStartMaxPercent;
                }
            }
        }

        EditorGUILayout.EndToggleGroup();
        DTGUIHelper.AddSpaceForNonU5(2);

        DTGUIHelper.StartGroupHeader();
        var newUseFades = EditorGUILayout.BeginToggleGroup(" Use Custom Fading", _variation.useFades);

        if (newUseFades != _variation.useFades)
        {
            AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "toggle Use Custom Fading");
            _variation.useFades = newUseFades;
        }
        DTGUIHelper.EndGroupHeader();

        if (_variation.useFades)
        {
            var newFadeIn = EditorGUILayout.Slider("Fade In Time (sec)", _variation.fadeInTime, 0f, 10f);
            if (newFadeIn != _variation.fadeInTime)
            {
                AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Fade In Time");
                _variation.fadeInTime = newFadeIn;
            }

            if (_variation.VarAudio.loop)
            {
                DTGUIHelper.ShowColorWarning("Looped clips cannot have a custom fade out.");
            }
            else
            {
                var newFadeOut = EditorGUILayout.Slider("Fade Out time (sec)", _variation.fadeOutTime, 0f, 10f);
                if (newFadeOut != _variation.fadeOutTime)
                {
                    AudioUndoHelper.RecordObjectPropertyForUndo(ref isDirty, _variation, "change Fade Out Time");
                    _variation.fadeOutTime = newFadeOut;
                }
            }
        }

        EditorGUILayout.EndToggleGroup();

        if (GUI.changed || isDirty)
        {
            EditorUtility.SetDirty(target);
        }

        //DrawDefaultInspector();
    }
예제 #22
0
        private static int SelectionGrid(IList <Block> items, int index)
        {
            Rect rect;
            int  xCount, yCount;

            index = SelectionGrid(items, index, out rect, out xCount, out yCount);
            float itemWidth  = rect.width / xCount;
            float itemHeight = rect.height / yCount;

            GUI.BeginGroup(rect);
            Vector2 mouse     = Event.current.mousePosition;
            int     posX      = Mathf.FloorToInt(mouse.x / itemWidth);
            int     posY      = Mathf.FloorToInt(mouse.y / itemHeight);
            int     realIndex = -1; // номер элемента под курсором

            if (posX >= 0 && posX < xCount && posY >= 0 && posY < yCount)
            {
                realIndex = posY * xCount + posX;
            }

            int dropX = Mathf.Clamp(posX, 0, xCount - 1);
            int dropY = Mathf.Clamp(posY, 0, yCount - 1);

            if (dropY == yCount - 1 && items.Count % xCount != 0)
            {
                dropX = Mathf.Clamp(dropX, 0, items.Count % xCount);
            }
            int dropIndex = dropY * xCount + dropX;   // ближайший элемент к курсору

            if (Event.current.type == EventType.MouseDrag && Event.current.button == 0 && realIndex == index)
            {
                DragAndDrop.PrepareStartDrag();
                DragAndDrop.objectReferences = new Object[0];
                DragAndDrop.paths            = new string[0];
                DragAndDrop.SetGenericData(DRAG_AND_DROP, new Container <int>(index));
                DragAndDrop.StartDrag("DragAndDrop");
                Event.current.Use();
            }

            if (Event.current.type == EventType.DragUpdated)
            {
                Container <int> data = (Container <int>)DragAndDrop.GetGenericData(DRAG_AND_DROP);
                if (data != null)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                    Event.current.Use();
                }
            }

            if (Event.current.type == EventType.DragPerform)
            {
                Container <int> oldIndex = (Container <int>)DragAndDrop.GetGenericData(DRAG_AND_DROP);

                if (dropIndex > oldIndex.value)
                {
                    dropIndex--;
                }
                dropIndex = Mathf.Clamp(dropIndex, 0, items.Count - 1);
                Insert(items, dropIndex, oldIndex);

                index = dropIndex;

                DragAndDrop.AcceptDrag();
                DragAndDrop.PrepareStartDrag();
                Event.current.Use();
            }

            if (Event.current.type == EventType.Repaint && DragAndDrop.visualMode == DragAndDropVisualMode.Link)
            {
                Vector2 pos      = new Vector2(2 + dropX * itemWidth, 2 + dropY * itemHeight);
                Rect    lineRect = new Rect(pos.x - 2, pos.y, 2, itemWidth - 2);
                EditorGUIUtils.FillRect(lineRect, Color.red);
            }
            GUI.EndGroup();

            return(index);
        }
예제 #23
0
 private void OnItemDragged(PrefabData prefabData)
 {
     DragAndDrop.PrepareStartDrag();
     DragAndDrop.objectReferences = new UnityEngine.Object[] { prefabData.GameObject };
     DragAndDrop.StartDrag("Dragging prefab");
 }
예제 #24
0
            // Drop area for Arbitrary Wardrobe recipes
            private bool AddRecipesDropAreaGUI(ref string errorMsg, Rect dropArea, List <string> recipes)
            {
                Event evt     = Event.current;
                bool  changed = false;

                //make the box clickable so that the user can select raceData assets from the asset selection window
                //TODO: cant make this work without layout errors. Anyone know how to fix?

                /*if (evt.type == EventType.MouseUp)
                 * {
                 *      if (dropArea.Contains(evt.mousePosition))
                 *      {
                 *              recipePickerID = EditorGUIUtility.GetControlID(new GUIContent("recipeObjectPicker"), FocusType.Passive);
                 *              EditorGUIUtility.ShowObjectPicker<UMARecipeBase>(null, false, "", recipePickerID);
                 *      }
                 * }
                 * if (evt.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == recipePickerID)
                 * {
                 *      UMARecipeBase tempRecipeAsset = EditorGUIUtility.GetObjectPickerObject() as UMARecipeBase;
                 *      if (tempRecipeAsset)
                 *      {
                 *              if (AddIfWardrobeRecipe(tempRecipeAsset, recipes))
                 *              {
                 *                      changed = true;
                 *                      errorMsg = "";
                 *              }
                 *              else
                 *                      errorMsg = "That recipe was not a Wardrobe recipe";
                 *
                 *      }
                 * }*/
                if (evt.type == EventType.DragUpdated)
                {
                    if (dropArea.Contains(evt.mousePosition))
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    }
                }
                if (evt.type == EventType.DragPerform)
                {
                    if (dropArea.Contains(evt.mousePosition))
                    {
                        DragAndDrop.AcceptDrag();

                        UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
                        bool allAdded = true;
                        for (int i = 0; i < draggedObjects.Length; i++)
                        {
                            if (draggedObjects[i])
                            {
                                UMARecipeBase tempRecipeAsset = draggedObjects[i] as UMARecipeBase;
                                if (tempRecipeAsset)
                                {
                                    if (AddIfWardrobeRecipe(tempRecipeAsset, recipes))
                                    {
                                        changed = true;
                                    }
                                    else
                                    {
                                        allAdded = false;
                                    }
                                    continue;
                                }

                                var path = AssetDatabase.GetAssetPath(draggedObjects[i]);
                                if (System.IO.Directory.Exists(path))
                                {
                                    RecursiveScanFoldersForAssets(path, recipes);
                                }
                            }
                        }
                        if (!allAdded)
                        {
                            errorMsg = "Some of the recipes you tried to add were not Wardrobe recipes";
                        }
                        else
                        {
                            errorMsg = "";
                        }
                    }
                }
                return(changed);
            }
예제 #25
0
        public void OnSceneGUI(SceneView sceneView)
        {
            int id = GUIUtility.GetControlID(ChiselDragAndDropManagerHash, FocusType.Keyboard);

            switch (Event.current.type)
            {
            case EventType.ValidateCommand:
            {
                // TODO:
                // "Copy", "Cut", "Paste", "Delete", "SoftDelete", "Duplicate", "FrameSelected", "FrameSelectedWithLock", "SelectAll", "Find" and "FocusProjectWindow".
                //Debug.Log(Event.current.commandName);
                break;
            }

            case EventType.DragUpdated:
            {
                if (dragAndDropOperation == null &&
                    DragAndDrop.activeControlID == 0)
                {
                    dragAndDropOperation = ChiselDragAndDropMaterial.AcceptDrag();
                    if (dragAndDropOperation != null)
                    {
                        DragAndDrop.activeControlID = id;
                    }
                }

                if (dragAndDropOperation != null)
                {
                    dragAndDropOperation.UpdateDrag();
                    DragAndDrop.visualMode      = DragAndDropVisualMode.Link;
                    DragAndDrop.activeControlID = id;
                    Event.current.Use();
                }
                break;
            }

            case EventType.DragPerform:
            {
                if (dragAndDropOperation != null)
                {
                    dragAndDropOperation.PerformDrag();
                    dragAndDropOperation = null;
                    DragAndDrop.AcceptDrag();
                    DragAndDrop.activeControlID = 0;
                    Event.current.Use();
                }
                break;
            }

            case EventType.DragExited:
            {
                if (dragAndDropOperation != null)
                {
                    dragAndDropOperation.CancelDrag();
                    dragAndDropOperation        = null;
                    DragAndDrop.activeControlID = 0;
                    HandleUtility.Repaint();
                    Event.current.Use();
                }
                break;
            }
            }
        }
예제 #26
0
    public override void OnInspectorGUI()
    {
        EditorGUILayout.HelpBox("This allows Easy Save to maintain references to objects in your scene.\n\nIt is automatically updated when you enter Playmode or build your project.", MessageType.Info);

        if (EditorGUILayout.Foldout(openReferences, "References") != openReferences)
        {
            openReferences = !openReferences;
            if (openReferences == true)
            {
                openReferences = EditorUtility.DisplayDialog("Are you sure?", "Opening this list will display every reference in the manager, which for larger projects can cause the Editor to freeze\n\nIt is strongly recommended that you save your project before continuing.", "Open References", "Cancel");
            }
        }

        // Make foldout drag-and-drop enabled for objects.
        if (GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
        {
            Event evt = Event.current;

            switch (evt.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                isDraggingOver = true;
                break;

            case EventType.DragExited:
                isDraggingOver = false;
                break;
            }

            if (isDraggingOver)
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                if (evt.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    Undo.RecordObject(mgr, "Add References to Easy Save 3 Reference List");
                    foreach (UnityEngine.Object obj in DragAndDrop.objectReferences)
                    {
                        mgr.Add(obj);
                    }
                    // Return now because otherwise we'll change the GUI during an event which doesn't allow it.
                    return;
                }
            }
        }

        if (openReferences)
        {
            EditorGUI.indentLevel++;

            foreach (var kvp in mgr.idRef)
            {
                EditorGUILayout.BeginHorizontal();

                var value = EditorGUILayout.ObjectField(kvp.Value, typeof(UnityEngine.Object), true);
                var key   = EditorGUILayout.LongField(kvp.Key);

                EditorGUILayout.EndHorizontal();

                if (value != kvp.Value || key != kvp.Key)
                {
                    Undo.RecordObject(mgr, "Change Easy Save 3 References");
                    // If we're deleting a value, delete it.
                    if (value == null)
                    {
                        mgr.Remove(key);
                    }
                    // Else, update the ID.
                    else
                    {
                        mgr.ChangeId(kvp.Key, key);
                    }
                    // Break, as removing or changing Dictionary items will make the foreach out of sync.
                    break;
                }
            }

            EditorGUI.indentLevel--;
        }

        mgr.openPrefabs = EditorGUILayout.Foldout(mgr.openPrefabs, "ES3Prefabs");
        if (mgr.openPrefabs)
        {
            EditorGUI.indentLevel++;

            foreach (var prefab in mgr.prefabs)
            {
                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.ObjectField(prefab, typeof(UnityEngine.Object), true);

                EditorGUILayout.EndHorizontal();
            }

            EditorGUI.indentLevel--;
        }

        EditorGUILayout.LabelField("Reference count", mgr.refId.Count.ToString());
        EditorGUILayout.LabelField("Prefab count", mgr.prefabs.Count.ToString());

        if (GUILayout.Button("Refresh"))
        {
            mgr.RefreshDependencies();
        }

        if (GUILayout.Button("Optimize"))
        {
            mgr.Optimize();
        }
    }
예제 #27
0
        public void Controls()
        {
            wantsMouseMove = true;
            Event e = Event.current;

            switch (e.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                if (e.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    graphEditor.OnDropObjects(DragAndDrop.objectReferences);
                }
                break;

            case EventType.MouseMove:
                //Keyboard commands will not get correct mouse position from Event
                lastMousePosition = e.mousePosition;
                break;

            case EventType.ScrollWheel:
                float oldZoom = zoom;
                if (e.delta.y > 0)
                {
                    zoom += 0.1f * zoom;
                }
                else
                {
                    zoom -= 0.1f * zoom;
                }
                if (NodeEditorPreferences.GetSettings().zoomToMouse)
                {
                    panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset);
                }
                break;

            case EventType.MouseDrag:
                if (e.button == 0)
                {
                    if (IsDraggingPort)
                    {
                        if (IsHoveringPort && hoveredPort.IsInput && draggedOutput.CanConnectTo(hoveredPort))
                        {
                            if (!draggedOutput.IsConnectedTo(hoveredPort))
                            {
                                draggedOutputTarget = hoveredPort;
                            }
                        }
                        else
                        {
                            draggedOutputTarget = null;
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldNode)
                    {
                        RecalculateDragOffsets(e);
                        currentActivity = NodeActivity.DragNode;
                        Repaint();
                    }
                    if (currentActivity == NodeActivity.DragNode)
                    {
                        // Holding ctrl inverts grid snap
                        bool gridSnap = NodeEditorPreferences.GetSettings().gridSnap;
                        if (e.control)
                        {
                            gridSnap = !gridSnap;
                        }

                        Vector2 mousePos = WindowToGridPosition(e.mousePosition);
                        // Move selected nodes with offset
                        for (int i = 0; i < Selection.objects.Length; i++)
                        {
                            if (Selection.objects[i] is XNode.Node)
                            {
                                XNode.Node node = Selection.objects[i] as XNode.Node;
                                Undo.RecordObject(node, "Moved Node");
                                Vector2 initial = node.position;
                                node.position = mousePos + dragOffset[i];
                                if (gridSnap)
                                {
                                    node.position.x = (Mathf.Round((node.position.x + 8) / 16) * 16) - 8;
                                    node.position.y = (Mathf.Round((node.position.y + 8) / 16) * 16) - 8;
                                }

                                // Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame.
                                Vector2 offset = node.position - initial;
                                if (offset.sqrMagnitude > 0)
                                {
                                    foreach (XNode.NodePort output in node.Outputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(output, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[output] = rect;
                                        }
                                    }

                                    foreach (XNode.NodePort input in node.Inputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(input, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[input] = rect;
                                        }
                                    }
                                }
                            }
                        }
                        // Move selected reroutes with offset
                        for (int i = 0; i < selectedReroutes.Count; i++)
                        {
                            Vector2 pos = mousePos + dragOffset[Selection.objects.Length + i];
                            if (gridSnap)
                            {
                                pos.x = (Mathf.Round(pos.x / 16) * 16);
                                pos.y = (Mathf.Round(pos.y / 16) * 16);
                            }
                            selectedReroutes[i].SetPoint(pos);
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldGrid)
                    {
                        currentActivity        = NodeActivity.DragGrid;
                        preBoxSelection        = Selection.objects;
                        preBoxSelectionReroute = selectedReroutes.ToArray();
                        dragBoxStart           = WindowToGridPosition(e.mousePosition);
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.DragGrid)
                    {
                        Vector2 boxStartPos = GridToWindowPosition(dragBoxStart);
                        Vector2 boxSize     = e.mousePosition - boxStartPos;
                        if (boxSize.x < 0)
                        {
                            boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x);
                        }
                        if (boxSize.y < 0)
                        {
                            boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y);
                        }
                        selectionBox = new Rect(boxStartPos, boxSize);
                        Repaint();
                    }
                }
                else if (e.button == 1 || e.button == 2)
                {
                    panOffset += e.delta * zoom;
                    isPanning  = true;
                }
                break;

            case EventType.MouseDown:
                Repaint();
                if (e.button == 0)
                {
                    draggedOutputReroutes.Clear();

                    if (IsHoveringPort)
                    {
                        if (hoveredPort.IsOutput)
                        {
                            draggedOutput     = hoveredPort;
                            autoConnectOutput = hoveredPort;
                        }
                        else
                        {
                            hoveredPort.VerifyConnections();
                            autoConnectOutput = null;
                            if (hoveredPort.IsConnected)
                            {
                                XNode.Node     node   = hoveredPort.node;
                                XNode.NodePort output = hoveredPort.Connection;
                                int            outputConnectionIndex = output.GetConnectionIndex(hoveredPort);
                                draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex);
                                hoveredPort.Disconnect(output);
                                draggedOutput       = output;
                                draggedOutputTarget = hoveredPort;
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                            }
                        }
                    }
                    else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                    {
                        // If mousedown on node header, select or deselect
                        if (!Selection.Contains(hoveredNode))
                        {
                            SelectNode(hoveredNode, e.control || e.shift);
                            if (!e.control && !e.shift)
                            {
                                selectedReroutes.Clear();
                            }
                        }
                        else if (e.control || e.shift)
                        {
                            DeselectNode(hoveredNode);
                        }

                        // Cache double click state, but only act on it in MouseUp - Except ClickCount only works in mouseDown.
                        isDoubleClick = (e.clickCount == 2);

                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    else if (IsHoveringReroute)
                    {
                        // If reroute isn't selected
                        if (!selectedReroutes.Contains(hoveredReroute))
                        {
                            // Add it
                            if (e.control || e.shift)
                            {
                                selectedReroutes.Add(hoveredReroute);
                            }
                            // Select it
                            else
                            {
                                selectedReroutes = new List <RerouteReference>()
                                {
                                    hoveredReroute
                                };
                                Selection.activeObject = null;
                            }
                        }
                        // Deselect
                        else if (e.control || e.shift)
                        {
                            selectedReroutes.Remove(hoveredReroute);
                        }
                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    // If mousedown on grid background, deselect all
                    else if (!IsHoveringNode)
                    {
                        currentActivity = NodeActivity.HoldGrid;
                        if (!e.control && !e.shift)
                        {
                            selectedReroutes.Clear();
                            Selection.activeObject = null;
                        }
                    }
                }
                break;

            case EventType.MouseUp:
                if (e.button == 0)
                {
                    //Port drag release
                    if (IsDraggingPort)
                    {
                        //If connection is valid, save it
                        if (draggedOutputTarget != null)
                        {
                            XNode.Node node = draggedOutputTarget.node;
                            if (graph.nodes.Count != 0)
                            {
                                draggedOutput.Connect(draggedOutputTarget);
                            }

                            // ConnectionIndex can be -1 if the connection is removed instantly after creation
                            int connectionIndex = draggedOutput.GetConnectionIndex(draggedOutputTarget);
                            if (connectionIndex != -1)
                            {
                                draggedOutput.GetReroutePoints(connectionIndex).AddRange(draggedOutputReroutes);
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                                EditorUtility.SetDirty(graph);
                            }
                        }
                        // Open context menu for auto-connection
                        else if (NodeEditorPreferences.GetSettings().dragToCreate&& autoConnectOutput != null)
                        {
                            GenericMenu menu = new GenericMenu();
                            graphEditor.AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                        }
                        //Release dragged connection
                        draggedOutput       = null;
                        draggedOutputTarget = null;
                        EditorUtility.SetDirty(graph);
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (currentActivity == NodeActivity.DragNode)
                    {
                        IEnumerable <XNode.Node> nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node);
                        foreach (XNode.Node node in nodes)
                        {
                            EditorUtility.SetDirty(node);
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (!IsHoveringNode)
                    {
                        // If click outside node, release field focus
                        if (!isPanning)
                        {
                            EditorGUI.FocusTextInControl(null);
                            EditorGUIUtility.editingTextField = false;
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }

                    // If click node header, select it.
                    if (currentActivity == NodeActivity.HoldNode && !(e.control || e.shift))
                    {
                        selectedReroutes.Clear();
                        SelectNode(hoveredNode, false);

                        // Double click to center node
                        if (isDoubleClick)
                        {
                            Vector2 nodeDimension = nodeSizes.ContainsKey(hoveredNode) ? nodeSizes[hoveredNode] / 2 : Vector2.zero;
                            panOffset = -hoveredNode.position - nodeDimension;
                        }
                    }

                    // If click reroute, select it.
                    if (IsHoveringReroute && !(e.control || e.shift))
                    {
                        selectedReroutes = new List <RerouteReference>()
                        {
                            hoveredReroute
                        };
                        Selection.activeObject = null;
                    }

                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                else if (e.button == 1 || e.button == 2)
                {
                    if (!isPanning)
                    {
                        if (IsDraggingPort)
                        {
                            draggedOutputReroutes.Add(WindowToGridPosition(e.mousePosition));
                        }
                        else if (currentActivity == NodeActivity.DragNode && Selection.activeObject == null && selectedReroutes.Count == 1)
                        {
                            selectedReroutes[0].InsertPoint(selectedReroutes[0].GetPoint());
                            selectedReroutes[0] = new RerouteReference(selectedReroutes[0].port, selectedReroutes[0].connectionIndex, selectedReroutes[0].pointIndex + 1);
                        }
                        else if (IsHoveringReroute)
                        {
                            ShowRerouteContextMenu(hoveredReroute);
                        }
                        else if (IsHoveringPort)
                        {
                            ShowPortContextMenu(hoveredPort);
                        }
                        else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                        {
                            if (!Selection.Contains(hoveredNode))
                            {
                                SelectNode(hoveredNode, false);
                            }
                            autoConnectOutput = null;
                            GenericMenu menu = new GenericMenu();
                            NodeEditor.GetEditor(hoveredNode, this).AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                            e.Use();     // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places.
                        }
                        else if (!IsHoveringNode)
                        {
                            autoConnectOutput = null;
                            GenericMenu menu = new GenericMenu();
                            graphEditor.AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                        }
                    }
                    isPanning = false;
                }
                // Reset DoubleClick
                isDoubleClick = false;
                break;

            case EventType.KeyDown:
                if (EditorGUIUtility.editingTextField)
                {
                    break;
                }
                else if (e.keyCode == KeyCode.F)
                {
                    Home();
                }
                if (NodeEditorUtilities.IsMac())
                {
                    if (e.keyCode == KeyCode.Return)
                    {
                        RenameSelectedNode();
                    }
                }
                else
                {
                    if (e.keyCode == KeyCode.F2)
                    {
                        RenameSelectedNode();
                    }
                }
                if (e.keyCode == KeyCode.A)
                {
                    if (Selection.objects.Any(x => graph.nodes.Contains(x as XNode.Node)))
                    {
                        foreach (XNode.Node node in graph.nodes)
                        {
                            DeselectNode(node);
                        }
                    }
                    else
                    {
                        foreach (XNode.Node node in graph.nodes)
                        {
                            SelectNode(node, true);
                        }
                    }
                    Repaint();
                }
                break;

            case EventType.ValidateCommand:
            case EventType.ExecuteCommand:
                if (e.commandName == "SoftDelete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (NodeEditorUtilities.IsMac() && e.commandName == "Delete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Duplicate")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        DuplicateSelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Copy")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        CopySelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Paste")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        PasteNodes(WindowToGridPosition(lastMousePosition));
                    }
                    e.Use();
                }
                Repaint();
                break;

            case EventType.Ignore:
                // If release mouse outside window
                if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid)
                {
                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                break;
            }
        }
        public override void DrawPreview(Rect previewArea)
        {
            if (REF_OBJECT != null)
            {
                if (REF_OBJECT_EDITOR == null)
                {
                    REF_OBJECT_EDITOR = CreateEditor(REF_OBJECT.animator.gameObject);
                }
                REF_OBJECT_EDITOR.OnPreviewGUI(previewArea, null);
            }
            else
            {
                EditorGUI.LabelField(
                    previewArea,
                    "Drop a scene Character here",
                    this.stylePreviewText
                    );
            }

            if (this.drawDragType == 2)
            {
                GUI.DrawTexture(
                    previewArea, TEX_PREVIEW_ACCEPT,
                    ScaleMode.StretchToFill, true
                    );
            }

            if (this.drawDragType == 1)
            {
                GUI.DrawTexture(
                    previewArea, TEX_PREVIEW_REJECT,
                    ScaleMode.StretchToFill, true
                    );
            }

            EventType currentEvent = Event.current.type;

            switch (currentEvent)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                this.drawDragType      = 1;
                if (!previewArea.Contains(Event.current.mousePosition))
                {
                    this.drawDragType = 0;
                    break;
                }

                if (DragAndDrop.objectReferences.Length == 1)
                {
                    GameObject dropObject = DragAndDrop.objectReferences[0] as GameObject;
                    if (dropObject != null)
                    {
                        CharacterAnimator animator = dropObject.GetComponentInChildren <CharacterAnimator>();
                        if (animator)
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                            this.drawDragType      = 2;
                            if (currentEvent == EventType.DragPerform)
                            {
                                this.drawDragType = 0;
                                DragAndDrop.AcceptDrag();
                                REF_OBJECT = animator;
                            }
                        }
                    }
                }
                Event.current.Use();
                break;

            case EventType.DragExited:
                this.drawDragType = 0;
                break;
            }
        }
예제 #29
0
        public override void    Draw(Rect r, DataDrawer data)
        {
            string      path        = data.GetPath();
            UnityObject unityObject = data.Value as UnityObject;
            int         controlID   = GUIUtility.GetControlID("NGObjectFieldHash".GetHashCode(), FocusType.Keyboard, r);

            if (Event.current.type == EventType.KeyDown &&
                Event.current.keyCode == KeyCode.Delete &&
                GUIUtility.keyboardControl == controlID)
            {
                UnityObject nullObject = new UnityObject(unityObject.type, 0);

                data.unityData.RecordChange(path, unityObject.type, unityObject, nullObject);
                data.unityData.AddPacket(new ClientUpdateFieldValuePacket(path, this.typeHandler.Serialize(nullObject.type, nullObject), this.typeHandler), p =>
                {
                    if (p.CheckPacketStatus() == true)
                    {
                        ByteBuffer buffer    = Utility.GetBBuffer((p as ServerUpdateFieldValuePacket).rawValue);
                        UnityObject newValue = this.typeHandler.Deserialize(Utility.GetBBuffer((p as ServerUpdateFieldValuePacket).rawValue), unityObject.type) as UnityObject;

                        unityObject.Assign(newValue.type, newValue.gameObjectInstanceID, newValue.instanceID, newValue.name);
                        Utility.RestoreBBuffer(buffer);
                    }
                });

                Event.current.Use();
            }

            if (r.Contains(Event.current.mousePosition) == true)
            {
                if (Event.current.type == EventType.MouseDown)
                {
                    if (Event.current.button == 1 && unityObject.instanceID != 0)
                    {
                        UnityObjectDrawer.unityData          = data.unityData;
                        UnityObjectDrawer.currentUnityObject = unityObject;

                        GenericMenu menu = new GenericMenu();

                        menu.AddItem(new GUIContent("Import asset"), false, this.ImportAsset);

                        menu.ShowAsContext();
                    }
                    else
                    {
                        UnityObjectDrawer.dragOriginPosition = Event.current.mousePosition;

                        // Initialize drag data.
                        DragAndDrop.PrepareStartDrag();

                        DragAndDrop.objectReferences = new Object[0];
                        DragAndDrop.SetGenericData("r", unityObject);
                    }
                }
                else if (Event.current.type == EventType.MouseDrag && (UnityObjectDrawer.dragOriginPosition - Event.current.mousePosition).sqrMagnitude >= Constants.MinStartDragDistance)
                {
                    DragAndDrop.StartDrag("Dragging Game Object");
                    Event.current.Use();
                }
                else if (Event.current.type == EventType.DragUpdated)
                {
                    UnityObject dragItem = DragAndDrop.GetGenericData("r") as UnityObject;

                    if (dragItem != null && dragItem.instanceID != unityObject.instanceID &&
                        (dragItem.type == null || unityObject.type == null || unityObject.type.IsAssignableFrom(dragItem.type) == true))
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                    }
                    else
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                    }

                    Event.current.Use();
                }
                else if (Event.current.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();

                    UnityObject dragItem = DragAndDrop.GetGenericData("r") as UnityObject;

                    data.unityData.RecordChange(path, unityObject.type, unityObject, dragItem);
                    data.unityData.AddPacket(new ClientUpdateFieldValuePacket(path, this.typeHandler.Serialize(dragItem.type, dragItem), this.typeHandler), p =>
                    {
                        if (p.CheckPacketStatus() == true)
                        {
                            ByteBuffer buffer    = Utility.GetBBuffer((p as ServerUpdateFieldValuePacket).rawValue);
                            UnityObject newValue = this.typeHandler.Deserialize(Utility.GetBBuffer((p as ServerUpdateFieldValuePacket).rawValue), unityObject.type) as UnityObject;

                            unityObject.Assign(newValue.type, newValue.gameObjectInstanceID, newValue.instanceID, newValue.name);
                            Utility.RestoreBBuffer(buffer);
                        }
                    });
                }
                else if (Event.current.type == EventType.Repaint &&
                         DragAndDrop.visualMode == DragAndDropVisualMode.Move)
                {
                    Rect r2 = r;

                    r2.width += r2.x;
                    r2.x      = 0F;

                    EditorGUI.DrawRect(r2, Color.yellow);
                }
            }

            float x     = r.x;
            float width = r.width;

            r.width = UnityObjectDrawer.PickerButtonWidth;
            r.x     = width - UnityObjectDrawer.PickerButtonWidth;

            if (Event.current.type == EventType.MouseDown &&
                r.Contains(Event.current.mousePosition) == true)
            {
                UnityObjectDrawer.unityData          = data.unityData;
                UnityObjectDrawer.currentUnityObject = unityObject;
                data.Inspector.Hierarchy.PickupResource(unityObject.type, path, UnityObjectDrawer.CreatePacket, UnityObjectDrawer.OnFieldUpdated, unityObject.instanceID);
                Event.current.Use();
            }

            r.width = width;
            r.x     = x;

            if (this.anim == null)
            {
                this.anim = new BgColorContentAnimator(data.Inspector.Repaint, 1F, 0F);
            }

            if (data.Inspector.Hierarchy.GetUpdateNotification(path) != NotificationPath.None)
            {
                this.anim.Start();
            }

            using (this.anim.Restorer(0F, .8F + this.anim.Value, 0F, 1F))
            {
                Utility.content.text = data.Name;

                Rect prefixRect = EditorGUI.PrefixLabel(r, Utility.content);

                if (unityObject.instanceID != 0)
                {
                    Utility.content.text = unityObject.name + " (" + unityObject.type.Name + ")";
                }
                else
                {
                    Utility.content.text = "None (" + unityObject.type.Name + ")";
                }

                if (GUI.Button(prefixRect, GUIContent.none, GUI.skin.label) == true)
                {
                    GUIUtility.keyboardControl = controlID;

                    if (unityObject.instanceID != 0 &&
                        typeof(Object).IsAssignableFrom(unityObject.type) == true)
                    {
                        if (this.lastClick + Constants.DoubleClickTime < Time.realtimeSinceStartup)
                        {
                            data.Inspector.Hierarchy.PingObject(unityObject.gameObjectInstanceID);
                        }
                        else
                        {
                            data.Inspector.Hierarchy.SelectGameObject(unityObject.gameObjectInstanceID);
                        }

                        this.lastClick = Time.realtimeSinceStartup;
                    }
                }

                if (Event.current.type == EventType.Repaint)
                {
                    GeneralStyles.UnityObjectPicker.Draw(prefixRect, Utility.content, controlID);
                }
            }
        }
예제 #30
0
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            SpriteParams spriteParams = (SpriteParams)target;
            Event        evt          = Event.current;
            Rect         drop_area    = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
            var          style        = new GUIStyle("box");

            if (EditorGUIUtility.isProSkin)
            {
                style.normal.textColor = Color.white;
            }
            // thanks to ProCamera2D for the idea - Unity does not provide any simple way to select multiple assets
            // and add them to a reorderable list, but drag/drop works well
            GUI.Box(drop_area, "\nAdd sprites by dragging them here!", style);
            switch (evt.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (!drop_area.Contains(evt.mousePosition))
                {
                    break;
                }
                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                if (evt.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    foreach (Object obj in DragAndDrop.objectReferences)
                    {
                        Sprite[] sprites = new Sprite[0];
                        if (obj is Texture2D)
                        {
                            Texture2D tex         = (Texture2D)obj;
                            string    spriteSheet = AssetDatabase.GetAssetPath(tex);
                            sprites = AssetDatabase.LoadAllAssetsAtPath(spriteSheet).OfType <Sprite>().ToArray();
                        }
                        else if (obj is Sprite)
                        {
                            sprites = new Sprite[] { obj as Sprite };
                        }
                        else if (obj is GameObject)
                        {
                            GameObject     go = (GameObject)obj;
                            SpriteRenderer sr = go.GetComponent <SpriteRenderer>();
                            if (sr && sr.sprite)
                            {
                                sprites = new Sprite[] { sr.sprite }
                            }
                            ;
                        }
                        foreach (Sprite s in sprites)
                        {
                            spriteParams.AddFrame(s);
                        }
                    }
                }
                break;
            }
            EditorGUILayout.Space();

            framesRL.DoLayoutList();

            serializedObject.ApplyModifiedProperties();
        }
    }
        private DragAndDropVisualMode CanDrop(TreeViewItem parent, int insertIndex, bool outside)
        {
            AssetFolderInfo parentFolder;

            if (parent == null)
            {
                //parentFolder = TreeView.treeModel.root;
                return(DragAndDropVisualMode.None);
            }
            else
            {
                parentFolder = ((TreeViewItem <AssetFolderInfo>)parent).data;
                if (parentFolder == TreeView.treeModel.root)
                {
                    return(DragAndDropVisualMode.None);
                }
            }

            if (DragAndDrop.objectReferences != null && DragAndDrop.objectReferences.Length > 0 && DragAndDrop.objectReferences.All(o => !CanDrop(o)))
            {
                return(DragAndDropVisualMode.None);
            }

            if (DragAndDrop.objectReferences != null && DragAndDrop.objectReferences.Length > 0 && DragAndDrop.objectReferences.Any(o => !IsFolder(o)))
            {
                if (insertIndex > -1)
                {
                    return(DragAndDropVisualMode.None);
                }
            }

            if (parentFolder.hasChildren)
            {
                var names = parentFolder.children.Select(c => c.name);

                var draggedRows = DragAndDrop.GetGenericData(AssetTreeView.k_GenericDragID) as List <TreeViewItem>;
                if (draggedRows != null)
                {
                    if (draggedRows.Any(item => names.Contains(((TreeViewItem <AssetInfo>)item).data.name)))
                    {
                        return(DragAndDropVisualMode.None);
                    }
                }
                else
                {
                    if (DragAndDrop.objectReferences.Any(item => names.Contains(item.name)))
                    {
                        return(DragAndDropVisualMode.None);
                    }
                }
            }

            if (parentFolder.Assets != null)
            {
                var names       = parentFolder.Assets.Select(c => c.name);
                var draggedRows = DragAndDrop.GetGenericData(AssetTreeView.k_GenericDragID) as List <TreeViewItem>;
                if (draggedRows != null)
                {
                    if (draggedRows.Any(item => names.Contains(((TreeViewItem <AssetInfo>)item).data.name)))
                    {
                        return(DragAndDropVisualMode.None);
                    }
                }
                else
                {
                    if (DragAndDrop.objectReferences.Any(item => names.Contains(item.name)))
                    {
                        return(DragAndDropVisualMode.None);
                    }
                }
            }

            if (outside)
            {
                var draggedRows = DragAndDrop.GetGenericData(AssetTreeView.k_GenericDragID) as List <TreeViewItem>;
                if (draggedRows != null)
                {
                    return(DragAndDropVisualMode.None);
                }
                else
                {
                    var allPath = DragAndDrop.objectReferences.Select(o => AssetDatabase.GetAssetPath(o));
                    if (allPath.All(path => !string.IsNullOrEmpty(path) && File.Exists(path)))
                    {
                        return(DragAndDropVisualMode.None);
                    }
                }
            }

            return(DragAndDropVisualMode.Copy);
        }
    void dragAndDropEvents()
    {
        Event evt = Event.current;

        foreach (Object dragged_object in DragAndDrop.objectReferences)
        {
            if (dragged_object.GetType() != typeof(Material))
            {
                return;
            }
        }

        Vector2 Origin = Camera.current.WorldToScreenPoint(lightRectOrigin);
        Vector2 Size   = Camera.current.WorldToScreenPoint(lightRectSize);


        Rect lightRect = new Rect(Origin.x, Origin.y, Size.x, Size.y);


        // To screen point
        Vector2 mouseWorld = Event.current.mousePosition;

        mouseWorld.y = Screen.height - (mouseWorld.y + 25);



        //Debug.Log(" rect " +lightRect);
        //Debug.Log(" mouse " +evt.mousePosition);

        if (!lastMat)
        {
            lastMat = light.LightMaterial;
        }


        bool isOver = lightRect.Contains(mouseWorld);

        //Debug.Log(isOver);


        switch (evt.type)
        {
        case EventType.MouseDown:
            DragAndDrop.PrepareStartDrag();                    // reset data
            break;

        case EventType.MouseUp:
            // Clean up, in case MouseDrag never occurred:
            DragAndDrop.PrepareStartDrag();
            //newMat = null;
            //if(!isOver){
            //	light.LightMaterial = lastMat;
            //}

            break;

        case EventType.DragUpdated:
            if (!isOver)
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                evt.Use();
            }
            else
            {
                foreach (Object dragged_object in DragAndDrop.objectReferences)
                {
                    newMat = (Material)dragged_object;
                    light.LightMaterial = newMat;
                }
            }

            break;



        case EventType.DragPerform:

            DragAndDrop.AcceptDrag();
            if (isOver)
            {
                foreach (Object dragged_object in DragAndDrop.objectReferences)
                {
                    newMat = (Material)dragged_object;
                    light.LightMaterial = newMat;
                }
                evt.Use();
            }
            break;
        }
    }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            Rect left, right;

            position.SplitHorizontallyWithRight(out left, out right, position.height);
            left.width -= 2;

            Object folderAsset = null;
            string folderPath  = "";

            SerializedProperty folderProp = property.FindPropertyRelative("_assetFolder");

            if (folderProp.hasMultipleDifferentValues)
            {
                EditorGUI.showMixedValue = true;
            }
            else
            {
                folderAsset = folderProp.objectReferenceValue;
                if (folderAsset != null)
                {
                    folderPath = AssetDatabase.GetAssetPath(folderAsset);
                }
            }

            EditorGUI.TextField(left, label, folderPath);

            var content = EditorGUIUtility.IconContent("Folder Icon");

            if (GUI.Button(right, content, GUIStyle.none))
            {
                string resultPath = PromptUserForPath(folderPath);
                if (!string.IsNullOrEmpty(resultPath))
                {
                    string relativePath = Utils.MakeRelativePath(Application.dataPath, resultPath);
                    var    asset        = AssetDatabase.LoadAssetAtPath <DefaultAsset>(relativePath);

                    string errorMessage;
                    if (!ValidatePath(resultPath, relativePath, out errorMessage))
                    {
                        EditorUtility.DisplayDialog("Invalid selection.", errorMessage, "OK");
                    }
                    else
                    {
                        folderProp.objectReferenceValue = asset;
                    }
                }
            }

            EditorGUI.showMixedValue = false;

            if (position.Contains(Event.current.mousePosition))
            {
                var    draggedObject = DragAndDrop.objectReferences.FirstOrDefault();
                string errorMessage;
                if (draggedObject != null)
                {
                    switch (Event.current.type)
                    {
                    case EventType.DragUpdated:
                        if (ValidateObject(draggedObject, out errorMessage))
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                        }
                        else
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                        }
                        break;

                    case EventType.DragPerform:
                        if (ValidateObject(draggedObject, out errorMessage))
                        {
                            DragAndDrop.AcceptDrag();
                            folderProp.objectReferenceValue = draggedObject;
                        }
                        break;
                    }
                }
            }
        }
        private DragAndDropVisualMode PerformDrop(TreeViewItem parent, int insertIndex, bool outside)
        {
            DragAndDrop.AcceptDrag();

            var draggedRows = DragAndDrop.GetGenericData(AssetTreeView.k_GenericDragID) as List <TreeViewItem>;

            if (draggedRows != null)
            {
                foreach (TreeViewItem <AssetInfo> dragged_object in draggedRows)
                {
                    if (!outside)
                    {
                        AssetFolderInfo folder = GetAssetFolderInfo(parent);
                        m_assetsGUI.InitIfNeeded();
                        m_assetsGUI.AddAssetToFolder(dragged_object.data, folder);
                    }
                }
            }
            else
            {
                m_moveDialogDisplayed = false;
                m_moveToNewLocation   = true;

                List <UnityObject> assets = new List <UnityObject>();
                foreach (UnityObject dragged_object in DragAndDrop.objectReferences)
                {
                    string path = AssetDatabase.GetAssetPath(dragged_object);



                    if (!string.IsNullOrEmpty(path) && File.Exists(path))
                    {
                        if (!outside)
                        {
                            assets.Add(dragged_object);
                        }
                    }
                    else
                    {
                        if (!CanDrop(dragged_object))
                        {
                            continue;
                        }

                        m_assetsGUI.InitIfNeeded();

                        AssetFolderInfo folder = CopyFolder(path, parent, insertIndex);
                        if (folder == null)
                        {
                            return(DragAndDropVisualMode.Rejected);
                        }

                        TreeView.SetSelection(new[] { folder.id }, TreeViewSelectionOptions.RevealAndFrame);

                        SelectedFolders = new[] { folder };
                        if (SelectedFoldersChanged != null)
                        {
                            SelectedFoldersChanged(this, EventArgs.Empty);
                        }
                    }
                }

                UnityObject[] assetsArray = assets.ToArray();
                if (assetsArray.Length > 0)
                {
                    MoveToNewLocationDialog(assetsArray);
                    AssetFolderInfo folder = GetAssetFolderInfo(parent);
                    m_assetsGUI.InitIfNeeded();
                    m_assetsGUI.AddAssetToFolder(assetsArray, folder, m_moveToNewLocation);
                }
            }

            return(DragAndDropVisualMode.Copy);
        }
        public void DropAreaGUI()
        {
            Event evt       = Event.current;
            Rect  drop_area = position; // GUILayoutUtility.GetRect (0.0f, 50.0f, GUILayout.ExpandWidth (true));

            drop_area.x = 0;
            drop_area.y = 0;

            Rect drop_area_all            = GetDropArea(drop_area, 0f, 0.1f);
            Rect drop_area_allbutname     = GetDropArea(drop_area, 0.1f, 0.2f);
            Rect drop_area_componentsonly = GetDropArea(drop_area, 0.2f, 0.6f);
            Rect drop_area_namelayertags  = GetDropArea(drop_area, 0.6f, 1f);
            Rect drop_area_fullwindow     = GetDropArea(drop_area, 0f, 1f);


            switch (evt.type)
            {
            case EventType.DragUpdated:
                _dragActive = true;
                break;

            case EventType.DragPerform:
                _dragActive = true;
                break;

            case EventType.DragExited:
                _dragActive = false;
                break;
            }

            bool isGameObject = DragAndDrop.objectReferences.Length > 0 &&
                                DragAndDrop.objectReferences[0] is GameObject;


            if (_dragActive)
            {
                //TODO

                /*if (isGameObject)
                 * {
                 *  GUI.Label(drop_area, "Drop in an area below!");
                 *  GUI.Box(drop_area_all, "Copy everything", Styles.dropFieldAll);
                 *  GUI.Box(drop_area_allbutname, "Copy every but the name", Styles.dropFieldComponents);
                 *  GUI.Box(drop_area_componentsonly, "Copy components & name", Styles.dropFieldAll);
                 *  GUI.Box(drop_area_namelayertags, "Copy name, layer and tags", Styles.dropFieldComponents);
                 * }
                 * else*/
                {
                    //GUI.Box(drop_area_fullwindow, "Drop the component here to add it to the search", Styles.dropFieldAll);
                    GUI.Box(drop_area_fullwindow, "Drop the object here to add it to the search", Styles.DropFieldAll);
                }
            }


            switch (evt.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:


                if (!drop_area.Contains(evt.mousePosition))
                {
                    return;
                }

                if (DragAndDrop.objectReferences[0] is Component)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                }
                else if (DragAndDrop.objectReferences[0] is GameObject)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                }
                else if (DragAndDrop.objectReferences[0] is MonoScript)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                }
                else
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                }


                if (evt.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();

                    foreach (Object dragged_object in DragAndDrop.objectReferences)
                    {
                        AddComponent(dragged_object);
                    }
                }

                break;
            }
        }
예제 #36
0
        static void OnSceneGUI(SceneView sceneView)
        {
            Event e = Event.current;

            if (Configure.IsEnableDragUIToScene && (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform))
            {
                //拉UI prefab或者图片入scene界面时帮它找到鼠标下的Canvas并挂在其上,若鼠标下没有画布就创建一个
                Object handleObj = DragAndDrop.objectReferences[0];
                if (!IsNeedHandleAsset(handleObj))
                {
                    //让系统自己处理
                    return;
                }
                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                //当松开鼠标时
                if (Event.current.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    foreach (var item in DragAndDrop.objectReferences)
                    {
                        HandleDragAsset(sceneView, item);
                    }
                }
                Event.current.Use();
            }
            else if (e.type == EventType.KeyDown && Configure.IsMoveNodeByArrowKey)
            {
                //按上按下要移动节点,因为默认情况下只是移动Scene界面而已
                foreach (var item in Selection.transforms)
                {
                    Transform trans = item;
                    if (trans != null)
                    {
                        bool handled = false;
                        if (e.keyCode == KeyCode.UpArrow)
                        {
                            Vector3 newPos = new Vector3(trans.localPosition.x, trans.localPosition.y + 1, trans.localPosition.z);
                            trans.localPosition = newPos;
                            handled             = true;
                        }
                        else if (e.keyCode == KeyCode.DownArrow)
                        {
                            Vector3 newPos = new Vector3(trans.localPosition.x, trans.localPosition.y - 1, trans.localPosition.z);
                            trans.localPosition = newPos;
                            handled             = true;
                        }
                        else if (e.keyCode == KeyCode.LeftArrow)
                        {
                            Vector3 newPos = new Vector3(trans.localPosition.x - 1, trans.localPosition.y, trans.localPosition.z);
                            trans.localPosition = newPos;
                            handled             = true;
                        }
                        else if (e.keyCode == KeyCode.RightArrow)
                        {
                            Vector3 newPos = new Vector3(trans.localPosition.x + 1, trans.localPosition.y, trans.localPosition.z);
                            trans.localPosition = newPos;
                            handled             = true;
                        }
                        if (handled)
                        {
                            Event.current.Use();
                        }
                    }
                }
            }
            //else if (e.type == EventType.MouseMove)//show cur mouse pos
            //{
            //    Camera cam = sceneView.camera;
            //    Vector3 mouse_abs_pos = e.mousePosition;
            //    mouse_abs_pos.y = cam.pixelHeight - mouse_abs_pos.y;
            //    mouse_abs_pos = sceneView.camera.ScreenToWorldPoint(mouse_abs_pos);
            //    Debug.Log("mouse_abs_pos : " + mouse_abs_pos.ToString());
            //}
            if (Event.current != null && Event.current.button == 1 && Event.current.type <= EventType.mouseUp && Configure.IsShowSceneMenu)
            {
                if (Selection.gameObjects == null || Selection.gameObjects.Length == 0 || Selection.gameObjects[0].transform is RectTransform)
                {
                    ContextMenu.AddCommonItems(Selection.gameObjects);
                    ContextMenu.Show();
                }
            }
        }
예제 #37
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            Texture browseIcon = EditorGUIUtility.Load("FMOD/SearchIconBlack.png") as Texture;
            Texture openIcon   = EditorGUIUtility.Load("FMOD/BrowserIcon.png") as Texture;
            Texture addIcon    = EditorGUIUtility.Load("FMOD/AddIcon.png") as Texture;

            label = EditorGUI.BeginProperty(position, label, property);
            SerializedProperty pathProperty = property;

            Event e = Event.current;

            if (e.type == EventType.DragPerform && position.Contains(e.mousePosition))
            {
                if (DragAndDrop.objectReferences.Length > 0 &&
                    DragAndDrop.objectReferences[0] != null &&
                    DragAndDrop.objectReferences[0].GetType() == typeof(EditorEventRef))
                {
                    pathProperty.stringValue = ((EditorEventRef)DragAndDrop.objectReferences[0]).Path;
                    GUI.changed = true;
                    e.Use();
                }
            }
            if (e.type == EventType.DragUpdated && position.Contains(e.mousePosition))
            {
                if (DragAndDrop.objectReferences.Length > 0 &&
                    DragAndDrop.objectReferences[0] != null &&
                    DragAndDrop.objectReferences[0].GetType() == typeof(EditorEventRef))
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                    DragAndDrop.AcceptDrag();
                    e.Use();
                }
            }

            float baseHeight = GUI.skin.textField.CalcSize(new GUIContent()).y;

            position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);

            GUIStyle buttonStyle = new GUIStyle(GUI.skin.button);

            buttonStyle.padding.top    = 1;
            buttonStyle.padding.bottom = 1;

            Rect addRect    = new Rect(position.x + position.width - addIcon.width - 7, position.y, addIcon.width + 7, baseHeight);
            Rect openRect   = new Rect(addRect.x - openIcon.width - 7, position.y, openIcon.width + 6, baseHeight);
            Rect searchRect = new Rect(openRect.x - browseIcon.width - 9, position.y, browseIcon.width + 8, baseHeight);
            Rect pathRect   = new Rect(position.x, position.y, searchRect.x - position.x - 3, baseHeight);

            EditorGUI.PropertyField(pathRect, pathProperty, GUIContent.none);

            if (GUI.Button(searchRect, new GUIContent(browseIcon, "Search"), buttonStyle))
            {
                var eventBrowser = EventBrowser.CreateInstance <EventBrowser>();

                eventBrowser.SelectEvent(property);
                var windowRect = position;
                windowRect.position = GUIUtility.GUIToScreenPoint(windowRect.position);
                windowRect.height   = openRect.height + 1;
                eventBrowser.ShowAsDropDown(windowRect, new Vector2(windowRect.width, 400));
            }
            if (GUI.Button(addRect, new GUIContent(addIcon, "Create New Event in Studio"), buttonStyle))
            {
                var addDropdown = EditorWindow.CreateInstance <CreateEventPopup>();

                addDropdown.SelectEvent(property);
                var windowRect = position;
                windowRect.position = GUIUtility.GUIToScreenPoint(windowRect.position);
                windowRect.height   = openRect.height + 1;
                addDropdown.ShowAsDropDown(windowRect, new Vector2(windowRect.width, 500));
            }
            if (GUI.Button(openRect, new GUIContent(openIcon, "Open In Browser"), buttonStyle) &&
                !string.IsNullOrEmpty(pathProperty.stringValue) &&
                EventManager.EventFromPath(pathProperty.stringValue) != null
                )
            {
                EventBrowser.ShowEventBrowser();
                var eventBrowser = EditorWindow.GetWindow <EventBrowser>();
                eventBrowser.JumpToEvent(pathProperty.stringValue);
            }

            if (!string.IsNullOrEmpty(pathProperty.stringValue) && EventManager.EventFromPath(pathProperty.stringValue) != null)
            {
                Rect foldoutRect = new Rect(position.x + 10, position.y + baseHeight, position.width, baseHeight);
                property.isExpanded = EditorGUI.Foldout(foldoutRect, property.isExpanded, "Event Properties");
                if (property.isExpanded)
                {
                    var style = new GUIStyle(GUI.skin.label);
                    style.richText = true;
                    EditorEventRef eventRef  = EventManager.EventFromPath(pathProperty.stringValue);
                    float          width     = style.CalcSize(new GUIContent("<b>Oneshot</b>")).x;
                    Rect           labelRect = new Rect(position.x, position.y + baseHeight * 2, width, baseHeight);
                    Rect           valueRect = new Rect(position.x + width + 10, position.y + baseHeight * 2, pathRect.width, baseHeight);

                    if (pathProperty.stringValue.StartsWith("{"))
                    {
                        GUI.Label(labelRect, new GUIContent("<b>Path</b>"), style);
                        EditorGUI.SelectableLabel(valueRect, eventRef.Path);
                    }
                    else
                    {
                        GUI.Label(labelRect, new GUIContent("<b>GUID</b>"), style);
                        EditorGUI.SelectableLabel(valueRect, eventRef.Guid.ToString("b"));
                    }
                    labelRect.y += baseHeight;
                    valueRect.y += baseHeight;

                    GUI.Label(labelRect, new GUIContent("<b>Banks</b>"), style);
                    GUI.Label(valueRect, string.Join(", ", eventRef.Banks.Select(x => x.Name).ToArray()));
                    labelRect.y += baseHeight;
                    valueRect.y += baseHeight;

                    GUI.Label(labelRect, new GUIContent("<b>Panning</b>"), style);
                    GUI.Label(valueRect, eventRef.Is3D ? "3D" : "2D");
                    labelRect.y += baseHeight;
                    valueRect.y += baseHeight;

                    GUI.Label(labelRect, new GUIContent("<b>Stream</b>"), style);
                    GUI.Label(valueRect, eventRef.IsStream.ToString());
                    labelRect.y += baseHeight;
                    valueRect.y += baseHeight;

                    GUI.Label(labelRect, new GUIContent("<b>Oneshot</b>"), style);
                    GUI.Label(valueRect, eventRef.IsOneShot.ToString());
                    labelRect.y += baseHeight;
                    valueRect.y += baseHeight;
                }
            }
            else
            {
                Rect labelRect = new Rect(position.x, position.y + baseHeight, position.width, baseHeight);
                GUI.Label(labelRect, new GUIContent("Event Not Found", EditorGUIUtility.Load("FMOD/NotFound.png") as Texture2D));
            }

            EditorGUI.EndProperty();
        }
예제 #38
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(position, label, property);

            EditorGUILayout.BeginHorizontal();

            bool show = property.isExpanded;

            UnityBuildGUIUtility.DropdownHeader("SceneList", ref show, false, GUILayout.ExpandWidth(true));
            property.isExpanded = show;

            EditorGUILayout.EndHorizontal();

            //Refresh all scene lists.
            for (int i = 0; i < BuildSettings.releaseTypeList.releaseTypes.Length; i++)
            {
                BuildReleaseType rt = BuildSettings.releaseTypeList.releaseTypes[i];
                rt.sceneList.Refresh();
            }

            list = property.FindPropertyRelative("enabledScenes");

            if (show)
            {
                EditorGUILayout.BeginVertical(UnityBuildGUIUtility.dropdownContentStyle);

                SerializedProperty platformProperty;
                string             fileGUID;
                string             filePath;
                string             sceneName = "N/A";
                if (list.arraySize > 0)
                {
                    platformProperty = list.GetArrayElementAtIndex(0);
                    fileGUID         = platformProperty.FindPropertyRelative("fileGUID").stringValue;
                    filePath         = AssetDatabase.GUIDToAssetPath(fileGUID);
                    sceneName        = Path.GetFileNameWithoutExtension(filePath);
                }

                EditorGUILayout.BeginHorizontal();

                show = list.isExpanded;
                UnityBuildGUIUtility.DropdownHeader(string.Format("Scenes ({0}) (First Scene: {1})", list.arraySize, sceneName), ref show, false, GUILayout.ExpandWidth(true));
                list.isExpanded = show;

                EditorGUILayout.EndHorizontal();

                if (show)
                {
                    for (int i = 0; i < list.arraySize; i++)
                    {
                        platformProperty = list.GetArrayElementAtIndex(i);
                        fileGUID         = platformProperty.FindPropertyRelative("fileGUID").stringValue;
                        filePath         = AssetDatabase.GUIDToAssetPath(fileGUID);
                        sceneName        = Path.GetFileNameWithoutExtension(filePath);

                        EditorGUILayout.BeginHorizontal();
                        EditorGUILayout.TextArea(sceneName + " (" + filePath + ")");

                        EditorGUI.BeginDisabledGroup(i == 0);
                        if (GUILayout.Button("↑↑", UnityBuildGUIUtility.helpButtonStyle))
                        {
                            list.MoveArrayElement(i, 0);
                        }
                        if (GUILayout.Button("↑", UnityBuildGUIUtility.helpButtonStyle))
                        {
                            list.MoveArrayElement(i, i - 1);
                        }
                        EditorGUI.EndDisabledGroup();

                        EditorGUI.BeginDisabledGroup(i == list.arraySize - 1);
                        if (GUILayout.Button("↓", UnityBuildGUIUtility.helpButtonStyle))
                        {
                            list.MoveArrayElement(i, i + 1);
                        }
                        EditorGUI.EndDisabledGroup();

                        if (GUILayout.Button("X", UnityBuildGUIUtility.helpButtonStyle))
                        {
                            list.DeleteArrayElementAtIndex(i);
                        }

                        property.serializedObject.ApplyModifiedProperties();

                        EditorGUILayout.EndHorizontal();
                    }
                }

                GUILayout.Space(20);

                Rect dropArea = GUILayoutUtility.GetRect(0, 50.0f, GUILayout.ExpandWidth(true));
                GUI.Box(dropArea, "Drag and Drop scene files here to add to list.", UnityBuildGUIUtility.dragDropStyle);
                Event currentEvent = Event.current;

                switch (currentEvent.type)
                {
                case EventType.DragUpdated:
                case EventType.DragPerform:
                    if (dropArea.Contains(currentEvent.mousePosition))
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                        if (currentEvent.type == EventType.DragPerform)
                        {
                            DragAndDrop.AcceptDrag();

                            foreach (Object obj in DragAndDrop.objectReferences)
                            {
                                if (obj.GetType() == typeof(UnityEditor.SceneAsset))
                                {
                                    string objFilepath = AssetDatabase.GetAssetPath(obj);
                                    string objGUID     = AssetDatabase.AssetPathToGUID(objFilepath);
                                    AddScene(objGUID);
                                }
                            }

                            if (list.arraySize >= AUTO_COLLAPSE_SIZE)
                            {
                                list.isExpanded = false;
                            }
                        }
                    }
                    break;
                }

                if (GUILayout.Button("Clear Scene List", GUILayout.ExpandWidth(true)))
                {
                    list.ClearArray();
                }

                if (GUILayout.Button("Add Scene File Directory", GUILayout.ExpandWidth(true)))
                {
                    GetSceneFileDirectory("Add Scene Files");
                }

                if (GUILayout.Button("Set First Scene by File", GUILayout.ExpandWidth(true)))
                {
                    SetFirstSceneByFile();
                }

                list.serializedObject.ApplyModifiedProperties();
                property.serializedObject.ApplyModifiedProperties();

                EditorGUILayout.EndVertical();
            }

            EditorGUI.EndProperty();
        }