private void OnAddDropDown(Rect buttonRect, ReorderableList list)
 {
     var menu = new GenericMenu();
     if (kModule._inputData.Length >= 2) return;
     if (kModule._inputData.Length == 0)
     {
         menu.AddItem(new GUIContent("Right Hand"),
                  false, OnClickHandler,
                  new DataParams() { jointType = KinectUIHandType.Right });
         menu.AddItem(new GUIContent("Left Hand"),
                  false, OnClickHandler,
                  new DataParams() { jointType = KinectUIHandType.Left });
     }
     else if (kModule._inputData.Length == 1)
     {
         DataParams param;
         string name;
         if (kModule._inputData[0].trackingHandType == KinectUIHandType.Left){
             param = new DataParams() { jointType = KinectUIHandType.Right };
             name = "Right Hand";
         }
         else
         {
             param = new DataParams() { jointType = KinectUIHandType.Left };
             name = "Left Hand";
         }
         menu.AddItem(new GUIContent(name),false, OnClickHandler, param);
     }
     menu.ShowAsContext();
 }
 public override void OnGUI(Rect pos, SerializedProperty prop, GUIContent label)
 {
     //SerializedProperty me = prop.FindPropertyRelative("this");
     //SerializedProperty scale = prop.FindPropertyRelative("scale");
     //SerializedProperty curve = prop.FindPropertyRelative("curve");
     //EditorGUI.LabelField(pos, "hi" + resources);
     var rowRect = new Rect(pos.x, pos.y, pos.width, base.GetPropertyHeight(prop, label));
     isFoldedOut = EditorGUI.Foldout(new Rect(rowRect.x, rowRect.y, rowRect.width - 20, rowRect.height), isFoldedOut, "Resources");
     if (isFoldedOut) {
         var resources = prop.FindPropertyRelative("Resources");
         if (GUI.Button(new Rect(rowRect.x + rowRect.width - 22, rowRect.y + 1, 22, rowRect.height - 2), "+")) {
             resources.InsertArrayElementAtIndex(resources.arraySize);
         }
         rowRect.y += rowRect.height;
         for (int i = 0; i < resources.arraySize; ++i) {
             var item = resources.GetArrayElementAtIndex(i);
             var minusClick = GUI.Button(new Rect(rowRect.x, rowRect.y, 22, rowRect.height), "-");
             EditorGUI.PropertyField(new Rect(rowRect.x + 20, rowRect.y, rowRect.width - 21, rowRect.height), item);
             if (minusClick) {
                 if (Event.current.button == 1) {
                     // Now create the menu, add items and show it
                     var menu = new GenericMenu();
                     if (i > 0)
                         menu.AddItem(new GUIContent("Move Up"), false, (itm) => { resources.MoveArrayElement((int)itm, (int)itm - 1); }, i);
                     if (i < resources.arraySize - 1)
                         menu.AddItem(new GUIContent("Move Down"), false, (itm) => { resources.MoveArrayElement((int)itm, (int)itm + 1); }, i);
                     menu.ShowAsContext();
                 } else {
                     resources.DeleteArrayElementAtIndex(i--);
                 }
             }
             rowRect.y += rowRect.height;
         }
     }
 }
    protected override void showHeaderContextMenu()
    {
        GenericMenu createMenu = new GenericMenu();
        createMenu.AddItem(new GUIContent("Select"), false, focusActor);
        createMenu.AddItem(new GUIContent("Delete"), false, delete);

        createMenu.ShowAsContext();
    }
Ejemplo n.º 4
0
	void OpenContextMenu()
	{
		GenericMenu menu = new GenericMenu();

		menu.AddItem (new GUIContent("Open As Floating Window", ""), false, Menu_OpenAsFloatingWindow);
		menu.AddItem (new GUIContent("Open As Dockable Window", ""), false, Menu_OpenAsDockableWindow);

		menu.ShowAsContext ();
	}		
Ejemplo n.º 5
0
    public void ClearConnectionMenu()
    {
        GenericMenu menu = new GenericMenu ();

        menu.AddSeparator ("ARE YOU SURE YOU WANT TO CLEAR?");
        menu.AddSeparator ("");
        menu.AddItem(new GUIContent ("Clear"), false, ClearConnections, "");
        menu.AddItem(new GUIContent ("Don't Clear"), false, DontClearConnections, "");

        menu.ShowAsContext ();
    }
	private void OnEnable() {
		list = new ReorderableList(serializedObject, 
		                           serializedObject.FindProperty("Waves"), 
		                           true, true, true, true);
		list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => {
			var element = list.serializedProperty.GetArrayElementAtIndex(index);
			rect.y += 2;
			EditorGUI.PropertyField(new Rect(rect.x, rect.y, 60, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("Type"), GUIContent.none);
			EditorGUI.PropertyField(new Rect(rect.x + 60, rect.y, rect.width - 60 - 30, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("Prefab"), GUIContent.none);
			EditorGUI.PropertyField(new Rect(rect.x + rect.width - 30, rect.y, 30, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("Count"), GUIContent.none);
		};
		list.drawHeaderCallback = (Rect rect) => {
			EditorGUI.LabelField(rect, "Monster Waves");
		};
		list.onSelectCallback = (ReorderableList l) => {
			var prefab = l.serializedProperty.GetArrayElementAtIndex(l.index).FindPropertyRelative("Prefab").objectReferenceValue as GameObject;
			if (prefab) EditorGUIUtility.PingObject(prefab.gameObject);
		};
		list.onCanRemoveCallback = (ReorderableList l) => {
			return l.count > 1;
		};
		list.onRemoveCallback = (ReorderableList l) => {
			if (EditorUtility.DisplayDialog("Warning!", "Are you sure you want to delete the wave?", "Yes", "No"))
			{
				ReorderableList.defaultBehaviours.DoRemoveButton(l);
			}
		};
		list.onAddCallback = (ReorderableList l) => {
			var index = l.serializedProperty.arraySize;
			l.serializedProperty.arraySize++;
			l.index = index;
			var element = l.serializedProperty.GetArrayElementAtIndex(index);
			element.FindPropertyRelative("Type").enumValueIndex = 0;
			element.FindPropertyRelative("Count").intValue = 20;
			element.FindPropertyRelative("Prefab").objectReferenceValue = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Mobs/Cube.prefab", typeof(GameObject)) as GameObject;
		};
		list.onAddDropdownCallback = (Rect buttonRect, ReorderableList l) => {
			var menu = new GenericMenu();
			var guids = AssetDatabase.FindAssets("", new[]{"Assets/Prefabs/Mobs"});
			foreach (var guid in guids) {
				var path = AssetDatabase.GUIDToAssetPath(guid);
				menu.AddItem(new GUIContent("Mobs/" + Path.GetFileNameWithoutExtension(path)), false, clickHandler, new WaveCreationParams() {Type = MobWave.WaveType.Mobs, Path = path});
			}
			guids = AssetDatabase.FindAssets("", new[]{"Assets/Prefabs/Bosses"});
			foreach (var guid in guids) {
				var path = AssetDatabase.GUIDToAssetPath(guid);
				menu.AddItem(new GUIContent("Bosses/" + Path.GetFileNameWithoutExtension(path)), false, clickHandler, new WaveCreationParams() {Type = MobWave.WaveType.Boss, Path = path});
			}
			menu.ShowAsContext();
		};
	}
    /// <summary>
    /// Create and show a context menu for adding new Timeline Tracks.
    /// </summary>
    protected override void addTrackContext()
    {
        TrackGroup trackGroup = TrackGroup.Behaviour as TrackGroup;
        if(trackGroup != null)
        {
            // Get the possible tracks that this group can contain.
            List<Type> trackTypes = trackGroup.GetAllowedTrackTypes();
            
            GenericMenu createMenu = new GenericMenu();

            // Get the attributes of each track.
            foreach (Type t in trackTypes)
            {
                MemberInfo info = t;
                string label = string.Empty;
                foreach (TimelineTrackAttribute attribute in info.GetCustomAttributes(typeof(TimelineTrackAttribute), true))
                {
                    label = attribute.Label;
                    break;
                }

                createMenu.AddItem(new GUIContent(string.Format("Add {0}", label)), false, addTrack, new TrackContextData(label, t, trackGroup));
            }

            createMenu.ShowAsContext();
        }
    }
Ejemplo n.º 8
0
    public static void CreateNodeMenu(Vector2 position, GenericMenu.MenuFunction2 MenuCallback)
    {
        GenericMenu menu = new GenericMenu();

        var assembly = Assembly.Load(new AssemblyName("Assembly-CSharp"));
        var paramTypes = (from t in assembly.GetTypes() where t.IsSubclassOfRawGeneric(typeof(AParameterNode<>)) && !t.IsAbstract select t).ToArray();
        var flowTypes = (from t in assembly.GetTypes() where t.IsSubclassOfRawGeneric(typeof(AFlowNode)) && !t.IsAbstract select t).ToArray();
        foreach(System.Type t in paramTypes) {
            menu.AddItem(new GUIContent(string.Format("Parameter Nodes/{0}", t.Name)), false, MenuCallback, new NodeCallbackData(position, t));
        }
        foreach(System.Type t in flowTypes) {
            menu.AddItem(new GUIContent(string.Format("Flow Nodes/{0}", t.Name)), false, MenuCallback, new NodeCallbackData(position, t));
        }
        menu.AddItem(new GUIContent("TaskNode"), false, MenuCallback, new NodeCallbackData(position, typeof(TaskNode)));
        menu.AddItem(new GUIContent("TreeNode"), false, MenuCallback, new NodeCallbackData(position, typeof(TreeNode)));
        menu.ShowAsContext();
    }
    private int controlID; // The control ID for this track control.

    /// <summary>
    /// Header Control 3 is typically the "Add" control.
    /// </summary>
    /// <param name="position">The position that this control is drawn at.</param>
    protected override void updateHeaderControl3(UnityEngine.Rect position)
    {
        TimelineTrack track = TargetTrack.Behaviour as TimelineTrack;
        if (track == null) return;

        Color temp = GUI.color;
        GUI.color = (track.GetTimelineItems().Length > 0) ? Color.green : Color.red;

        controlID = GUIUtility.GetControlID(track.GetInstanceID(), FocusType.Passive, position);

        if (GUI.Button(position, string.Empty, TrackGroupControl.styles.addIcon))
        {
            // Get the possible items that this track can contain.
            List<Type> trackTypes = track.GetAllowedCutsceneItems();

            if (trackTypes.Count == 1)
            {
                // Only one option, so just create it.
                ContextData data = getContextData(trackTypes[0]);
                if (data.PairedType == null)
                {
                    addCutsceneItem(data);
                }
                else
                {
                    showObjectPicker(data);
                }
            }
            else if (trackTypes.Count > 1)
            {
                // Present context menu for selection.
                GenericMenu createMenu = new GenericMenu();
                foreach (Type t in trackTypes)
                {
                    ContextData data = getContextData(t);

                    createMenu.AddItem(new GUIContent(string.Format("{0}/{1}", data.Category, data.Label)), false, addCutsceneItem, data);
                }
                createMenu.ShowAsContext();
            }
        }

        // Handle the case where the object picker has a value selected.
        if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "ObjectSelectorClosed")
        {
            if (EditorGUIUtility.GetObjectPickerControlID() == controlID)
            {
                UnityEngine.Object pickedObject = EditorGUIUtility.GetObjectPickerObject();

                if(pickedObject != null)
                    addCutsceneItem(savedData, pickedObject);

                Event.current.Use();
            }
        }

        GUI.color = temp;
    }
    protected override void showContextMenu(Behaviour behaviour)
    {
        CinemaActorClipCurve clipCurve = behaviour as CinemaActorClipCurve;
        if (clipCurve == null) return;

        List<KeyValuePair<string, string>> currentCurves = new List<KeyValuePair<string, string>>();
        foreach (MemberClipCurveData data in clipCurve.CurveData)
        {
            KeyValuePair<string, string> curveStrings = new KeyValuePair<string, string>(data.Type, data.PropertyName);
            currentCurves.Add(curveStrings);
        }

        GenericMenu createMenu = new GenericMenu();

        if (clipCurve.Actor != null)
        {
            Component[] components = DirectorHelper.getValidComponents(clipCurve.Actor.gameObject);

            for (int i = 0; i < components.Length; i++)
            {
                Component component = components[i];
                MemberInfo[] members = DirectorHelper.getValidMembers(component);
                for (int j = 0; j < members.Length; j++)
                {
                    AddCurveContext context = new AddCurveContext();
                    context.clipCurve = clipCurve;
                    context.component = component;
                    context.memberInfo = members[j];
                    if (!currentCurves.Contains(new KeyValuePair<string, string>(component.GetType().Name, members[j].Name)))
                    {
                        createMenu.AddItem(new GUIContent(string.Format("Add Curve/{0}/{1}", component.GetType().Name, DirectorHelper.GetUserFriendlyName(component, members[j]))), false, addCurve, context);
                    }
                }
            }
            createMenu.AddSeparator(string.Empty);
        }
        createMenu.AddItem(new GUIContent("Copy"), false, copyItem, behaviour);
        createMenu.AddSeparator(string.Empty);
        createMenu.AddItem(new GUIContent("Clear"), false, deleteItem, clipCurve);
        createMenu.ShowAsContext();
    }
Ejemplo n.º 11
0
    public static void DrawAddTabGUI(List<AlloyTabAdd> tabsToAdd) {
        if (tabsToAdd.Count <= 0) {
            return;
        }
        
        
        GUI.color = new Color(0.8f, 0.8f, 0.8f, 0.8f);
        GUILayout.Label("");
        var rect = GUILayoutUtility.GetLastRect();

        rect.x -= 35.0f;
        rect.width += 10.0f;

        GUI.color = Color.clear;
        bool add = GUI.Button(rect, new GUIContent(""), "Box");
        GUI.color = new Color(0.8f, 0.8f, 0.8f, 0.8f);
        Rect subRect = rect;

        foreach (var tab in tabsToAdd) {
            GUI.color = tab.Color;
            GUI.Box(subRect, "", "ShurikenModuleTitle");

            subRect.x += rect.width / tabsToAdd.Count;
            subRect.width -= rect.width / tabsToAdd.Count;
        }

        GUI.color = new Color(0.8f, 0.8f, 0.8f, 0.8f);

        var delRect = rect;
        delRect.xMin = rect.xMax;
        delRect.xMax += 40.0f;

        if (GUI.Button(delRect, "", "ShurikenModuleTitle") || add) {
            var menu = new GenericMenu();

            foreach (var tab in tabsToAdd) {
                menu.AddItem(new GUIContent(tab.Name), false, tab.Enable);
            }

            menu.ShowAsContext();
        }

        delRect.x += 10.0f;

        GUI.Label(delRect, "+");
        rect.x += EditorGUIUtility.currentViewWidth / 2.0f - 30.0f;

        // Ensures tab text is always white, even when using light skin in pro.
        GUI.color = EditorGUIUtility.isProSkin ? new Color(0.7f, 0.7f, 0.7f) : new Color(0.9f, 0.9f, 0.9f);
        GUI.Label(rect, "Add tab", EditorStyles.whiteLabel);
        GUI.color = Color.white;
    }
    protected override void showContextMenu(Behaviour behaviour)
    {
        CinemaShot shot = behaviour as CinemaShot;
        if (shot == null) return;

        Camera[] cameras = GameObject.FindObjectsOfType<Camera>();
        
        GenericMenu createMenu = new GenericMenu();
        createMenu.AddItem(new GUIContent("Focus"), false, focusShot, shot);
        foreach (Camera c in cameras)
        {
            
            ContextSetCamera arg = new ContextSetCamera();
            arg.shot = shot;
            arg.camera = c;
            createMenu.AddItem(new GUIContent(string.Format(MODIFY_CAMERA, c.gameObject.name)), false, setCamera, arg);
        }
        createMenu.AddSeparator(string.Empty);
        createMenu.AddItem(new GUIContent("Copy"), false, copyItem, behaviour);
        createMenu.AddSeparator(string.Empty);
        createMenu.AddItem(new GUIContent("Clear"), false, deleteItem, shot);
        createMenu.ShowAsContext();
    }
Ejemplo n.º 13
0
 void OnGUI()
 {
     windowRect = new Rect(0, 0, Screen.width, Screen.height);
     if(Event.current.type == EventType.ContextClick)
     {
         Vector2 mousePos = Event.current.mousePosition;
         if(windowRect.Contains(mousePos))
         {
             GenericMenu menu = new GenericMenu();
             menu.AddItem(new GUIContent("CreateCube"), false, createMenu, "createCube");
             menu.ShowAsContext();
         }
     }
 }
 private void ShowAddTriggermenu()
 {
   GenericMenu genericMenu = new GenericMenu();
   for (int index1 = 0; index1 < this.m_EventTypes.Length; ++index1)
   {
     bool flag = true;
     for (int index2 = 0; index2 < this.m_DelegatesProperty.arraySize; ++index2)
     {
       if (this.m_DelegatesProperty.GetArrayElementAtIndex(index2).FindPropertyRelative("eventID").enumValueIndex == index1)
         flag = false;
     }
     if (flag)
       genericMenu.AddItem(this.m_EventTypes[index1], false, new GenericMenu.MenuFunction2(this.OnAddNewSelected), (object) index1);
     else
       genericMenu.AddDisabledItem(this.m_EventTypes[index1]);
   }
   genericMenu.ShowAsContext();
   Event.current.Use();
 }
    protected override void showBodyContextMenu(Event evt)
    {
        MultiCurveTrack itemTrack = TargetTrack.Behaviour as MultiCurveTrack;
        if (itemTrack == null) return;

        Behaviour b = DirectorCopyPaste.Peek();

        PasteContext pasteContext = new PasteContext(evt.mousePosition, itemTrack);
        GenericMenu createMenu = new GenericMenu();
        if (b != null && DirectorHelper.IsTrackItemValidForTrack(b, itemTrack))
        {
            createMenu.AddItem(new GUIContent("Paste"), false, pasteItem, pasteContext);
        }
        else
        {
            createMenu.AddDisabledItem(new GUIContent("Paste"));
        }
        createMenu.ShowAsContext();
    }
    private void BuildMenu(GenericMenu menu, Type type, string itemVisiblePath, string itemInternalPath, bool addSelf, int depth, GenericMenu.MenuFunction2 function)
    {
        if (addSelf) {
            menu.AddItem (new GUIContent (itemVisiblePath + "/" + type.Name), false, function, itemInternalPath);
        }
        var members = UTComponentScanner.FindPublicWritableMembersOf (type);
        foreach (var memberInfo in members.MemberInfos) {

            var newInternalPath = string.IsNullOrEmpty (itemInternalPath) ? memberInfo.Name : itemInternalPath + "." + memberInfo.Name;
            var newVisiblePath = string.IsNullOrEmpty (itemVisiblePath) ? memberInfo.Name : itemVisiblePath + "/" + memberInfo.Name;
            if (memberInfo.DeclaringType != typeof(Component)) {
                    var memberInfoType = UTInternalCall.GetMemberType (memberInfo);
                    if (UTInternalCall.HasMembers (memberInfoType) && depth < 2) {
                        BuildMenu (menu, memberInfoType, newVisiblePath, newInternalPath, UTInternalCall.IsWritable (memberInfo), depth + 1, function);
                    } else {
                        menu.AddItem (new GUIContent (newVisiblePath), false, function, newInternalPath);
                    }
            }
        }
    }
Ejemplo n.º 17
0
	void Selector(SerializedProperty property) {
		SpineBone attrib = (SpineBone)attribute;
		SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
		if (data == null)
			return;

		GenericMenu menu = new GenericMenu();

		menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
		menu.AddSeparator("");

		for (int i = 0; i < data.Bones.Count; i++) {
			string name = data.Bones.Items[i].Name;
			if (name.StartsWith(attrib.startsWith))
				menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
		}

		menu.ShowAsContext();
	}
Ejemplo n.º 18
0
        public virtual void Render(int id, Rect rect, int headerWidth, FrameRange viewRange, float pixelsPerFrame)
        {
            rect.y += _offsetAnim.value.y;

            _rect = rect;

            Rect viewRect = rect;

            viewRect.y     += _offsetAnim.value.y;
            viewRect.xMax   = headerWidth;
            viewRect.xMin   = viewRect.xMax - 16;
            viewRect.height = 16;

            if (_track.CanTogglePreview())
            {
                if (Event.current.type == EventType.MouseDown)
                {
                    if (viewRect.Contains(Event.current.mousePosition))
                    {
                        if (Event.current.button == 0)                          // left click?
                        {
                            _track.IsPreviewing = !_track.IsPreviewing;
                            FUtility.RepaintGameView();
                            Event.current.Use();
                        }
                    }
                }
            }

            Rect trackHeaderRect = rect;

            trackHeaderRect.xMax = headerWidth;

            bool selected = _isSelected;

            if (selected)
            {
                Color c = FGUI.GetSelectionColor();
                GUI.color = c;
                GUI.DrawTexture(trackHeaderRect, EditorGUIUtility.whiteTexture);
                GUI.color = FGUI.GetTextColor();

//				Debug.Log( GUI.color );
            }

            Rect trackLabelRect = trackHeaderRect;

            trackLabelRect.xMin += 10;

            GUI.Label(trackLabelRect, new GUIContent(_track.name), FGUI.GetTrackHeaderStyle());

            rect.xMin = trackHeaderRect.xMax;

            FrameRange validKeyframeRange = new FrameRange(0, SequenceEditor.GetSequence().Length);

            for (int i = 0; i != _eventEditors.Count; ++i)
            {
                if (i == 0)
                {
                    validKeyframeRange.Start = 0;
                }
                else
                {
                    validKeyframeRange.Start = _eventEditors[i - 1]._evt.End;
                }

                if (i == _eventEditors.Count - 1)
                {
                    validKeyframeRange.End = SequenceEditor.GetSequence().Length;
                }
                else
                {
                    validKeyframeRange.End = _eventEditors[i + 1]._evt.Start;
                }
                _eventEditors[i].Render(rect, viewRange, pixelsPerFrame, validKeyframeRange);
            }

            switch (Event.current.type)
            {
            case EventType.ContextClick:
                if (trackHeaderRect.Contains(Event.current.mousePosition))
                {
                    GenericMenu menu = new GenericMenu();
                    menu.AddItem(new GUIContent("Duplicate Track"), false, DuplicateTrack);
                    menu.AddItem(new GUIContent("Delete Track"), false, DeleteTrack);
                    menu.ShowAsContext();
                    Event.current.Use();
                }
                break;

            case EventType.MouseDown:
                if (EditorGUIUtility.hotControl == 0 && trackHeaderRect.Contains(Event.current.mousePosition))
                {
                    if (Event.current.button == 0)                      // selecting
                    {
                        if (Event.current.control)
                        {
                            if (IsSelected())
                            {
                                SequenceEditor.Deselect(this);
                            }
                            else
                            {
                                SequenceEditor.Select(this);
                            }
                        }
                        else if (Event.current.shift)
                        {
                            SequenceEditor.Select(this);
                        }
                        else
                        {
                            SequenceEditor.SelectExclusive(this);
                            _timelineEditor.StartTrackDrag(this);
                            _offsetAnim.value           = _offsetAnim.target = new Vector2(0, rect.yMin) - Event.current.mousePosition;
                            EditorGUIUtility.hotControl = id;
                        }
                        Event.current.Use();
                    }
                }
                break;

            case EventType.MouseUp:
                if (EditorGUIUtility.hotControl == id)
                {
                    EditorGUIUtility.hotControl = 0;
                    _offsetAnim.value           = _offsetAnim.target = Vector2.zero;

                    _timelineEditor.StopTrackDrag();

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

            case EventType.MouseDrag:
                if (EditorGUIUtility.hotControl == id)
                {
                    SequenceEditor.Repaint();
                    Event.current.Use();
                }
                break;
            }

            if (_track.CanTogglePreview())
            {
                GUI.color = FGUI.GetTextColor();

                if (!_track.IsPreviewing)
                {
                    Color c = GUI.color;
                    c.a       = 0.3f;
                    GUI.color = c;
                }

                GUI.DrawTexture(viewRect, _previewIcon);

                GUI.color = Color.white;
            }

#if UNITY_4_5
            if (_offsetAnim.isAnimating)
            {
                SequenceEditor.Repaint();
            }
#endif
        }
        static void DoLaunchButtons(
            bool isPlasticExeAvailable,
            WorkspaceInfo wkInfo,
            bool isGluonMode)
        {
            //TODO: Codice - beta: hide the diff button until the behavior is implemented

            /*GUILayout.Button(PlasticLocalization.GetString(
             *  PlasticLocalization.Name.DiffWindowMenuItemDiff),
             *  EditorStyles.toolbarButton,
             *  GUILayout.Width(UnityConstants.REGULAR_BUTTON_WIDTH));*/

            if (isGluonMode)
            {
                var label = PlasticLocalization.GetString(PlasticLocalization.Name.ConfigureGluon);
                if (DrawActionButton.For(label))
                {
                    LaunchTool.OpenWorkspaceConfiguration(wkInfo, isGluonMode);
                }
            }
            else
            {
                var label = PlasticLocalization.GetString(PlasticLocalization.Name.LaunchBranchExplorer);
                if (DrawActionButton.For(label))
                {
                    LaunchTool.OpenBranchExplorer(wkInfo, isGluonMode);
                }
            }

            string openToolText = isGluonMode ?
                                  PlasticLocalization.GetString(PlasticLocalization.Name.LaunchGluonButton) :
                                  PlasticLocalization.GetString(PlasticLocalization.Name.LaunchPlasticButton);

            if (DrawActionButton.For(openToolText))
            {
                LaunchTool.OpenGUIForMode(wkInfo, isGluonMode);
            }

            if (GUILayout.Button(new GUIContent(
                                     EditorGUIUtility.IconContent("settings")), EditorStyles.toolbarButton))
            {
                GenericMenu menu = new GenericMenu();
                menu.AddItem(
                    new GUIContent(
                        PlasticLocalization.GetString(
                            PlasticLocalization.Name.InviteMembers)),
                    false,
                    InviteMemberButton_clicked,
                    null);

                // If the user has the simplified UI key of type .txt in the Assets folder
                // TODO: Remove when Simplified UI is complete
                if (AssetDatabase.FindAssets("simplifieduikey t:textasset", new[] { "Assets" }).Any())
                {
                    menu.AddItem(new GUIContent("Try Simplified UI"),
                                 false,
                                 TrySimplifiedUIButton_Clicked,
                                 null);
                }

                menu.AddSeparator("");

                menu.AddItem(
                    new GUIContent(
                        PlasticLocalization.GetString(
                            PlasticLocalization.Name.TurnOffPlasticSCM)),
                    false,
                    TurnOffPlasticButton_Clicked,
                    null);

                menu.ShowAsContext();
            }
        }
        void OnGUI()
        {
            Styles.Init();

            if (m_ConversionReadyState == ConversionReadyState.NoActionRequired ||
                m_ConversionReadyState == ConversionReadyState.ConversionRan)
            {
                if (!string.IsNullOrEmpty(m_ConversionLog))
                {
                    m_ConversionLogScroll = EditorGUILayout.BeginScrollView(m_ConversionLogScroll);
                    GUILayout.Label(m_ConversionLog, EditorStyles.wordWrappedLabel);
                    EditorGUILayout.EndScrollView();
                }
                else
                {
                    GUI.Label(new Rect(0, 0, position.width, position.height), "ProBuilder is up to date!",
                              EditorStyles.centeredGreyMiniLabel);

                    if (Event.current.type == EventType.ContextClick)
                    {
                        var menu = new GenericMenu();
                        menu.AddItem(new GUIContent("Find and replace deprecated Asset IDs"), false, () =>
                        {
                            var log = new StringBuilder();
                            RemapAssetIds(log);
                            Debug.Log(log);
                        });
                        menu.ShowAsContext();
                    }
                }
                return;
            }
            else if ((m_ConversionReadyState & ConversionReadyState.AssetStoreInstallFound) > 0)
            {
                GUILayout.Label("Obsolete Files to Delete", EditorStyles.boldLabel);

                m_AssetTreeRect = GUILayoutUtility.GetRect(position.width, 128, GUILayout.ExpandHeight(true));

                EditorGUI.BeginChangeCheck();

                DrawTreeSettings();

                m_AssetsToDeleteTreeView.OnGUI(m_AssetTreeRect);

                if (EditorGUI.EndChangeCheck())
                {
                    m_ConversionReadyState = GetReadyState();
                }
            }
            else if ((m_ConversionReadyState & ConversionReadyState.DeprecatedAssetIdsFound) > 0)
            {
                var deprecatedIdsRect = GUILayoutUtility.GetRect(position.width, 32, GUILayout.ExpandHeight(true));
                GUI.Label(deprecatedIdsRect, "References to old ProBuilder install found.\n\nProject is ready for conversion.",
                          EditorStyles.centeredGreyMiniLabel);
            }

            if ((m_ConversionReadyState & ConversionReadyState.SerializationError) > 0)
            {
                EditorGUILayout.HelpBox(
                    "Cannot update project with binary or mixed serialization.\n\nPlease swith to ForceText serialization to proceed (you may switch back to ForceBinary or Mixed after the conversion process).",
                    MessageType.Error);

                SerializationMode serializationMode = EditorSettings.serializationMode;

                EditorGUI.BeginChangeCheck();

                serializationMode = (SerializationMode)EditorGUILayout.EnumPopup("Serialization Mode", serializationMode);

                if (EditorGUI.EndChangeCheck())
                {
                    EditorSettings.serializationMode = serializationMode;
                    m_ConversionReadyState           = GetReadyState();
                }
            }

            if ((m_ConversionReadyState & ConversionReadyState.AssetStoreDeleteError) > 0)
            {
                EditorGUILayout.HelpBox(
                    "Cannot update project without removing ProBuilder/Classes and ProBuilder/Editor directories.", MessageType.Error);
            }

            if ((m_ConversionReadyState & ConversionReadyState.AssetStoreDeleteWarning) > 0)
            {
                EditorGUILayout.HelpBox(
                    "Some old ProBuilder files are not marked for deletion. This may cause errors after the conversion process is complete.\n\nTo clear this error use the settings icon to reset the Assets To Delete tree.",
                    MessageType.Warning);
            }

            GUI.enabled =
                (m_ConversionReadyState & (ConversionReadyState.AssetStoreDeleteError | ConversionReadyState.SerializationError)) ==
                ConversionReadyState.Ready;

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Convert to ProBuilder 4", Styles.convertButton))
            {
                DoConversion();
                GUIUtility.ExitGUI();
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            #if UNITY_2018_3_OR_NEWER
            GUILayout.Space(16);
            #endif
            GUI.enabled = true;
        }
        internal static void DrawConditions(SerializedObject serializedObject, SerializedProperty conditionsProperty, GameConditionReference[] conditionReferences,
                                            ref GameConditionEditor[] conditionEditors, List <ClassDetailsAttribute> classDetails, string heading = null, string tooltip = null)
        {
            if (heading != null)
            {
                EditorGUILayout.Space();
                EditorGUILayout.LabelField(new GUIContent(heading, tooltip), EditorStyles.boldLabel);
            }

            EditorGUILayout.Space();

            conditionEditors = GameConditionEditorHelper.CheckAndCreateSubEditors(conditionEditors, conditionReferences, serializedObject, conditionsProperty);

            if (conditionsProperty.arraySize == 0)
            {
                EditorGUILayout.LabelField("No conditions specified.", GuiStyles.CenteredLabelStyle, GUILayout.ExpandWidth(true));
            }
            else
            {
                // Display all items - use a for loop rather than a foreach loop in case of deletion.
                for (var i = 0; i < conditionsProperty.arraySize; i++)
                {
                    EditorGUILayout.BeginVertical(GUI.skin.box);

                    if (conditionEditors[i] == null)
                    {
                        var conditionReference         = conditionsProperty.GetArrayElementAtIndex(i);
                        var conditionClassNameProperty = conditionReference.FindPropertyRelative("_className");
                        EditorGUILayout.LabelField("Error loading " + conditionClassNameProperty.stringValue);
                    }
                    else
                    {
                        EditorGUILayout.BeginHorizontal();
                        var currentConditionClass = classDetails.Find(x => conditionReferences[i].ScriptableObject.GetType() == x.ClassType);
                        EditorGUILayout.LabelField(new GUIContent(currentConditionClass.Name, currentConditionClass.Tooltip));
                        if (GUILayout.Button("-", GUILayout.Width(RemoveButtonWidth)))
                        {
                            conditionsProperty.DeleteArrayElementAtIndex(i);
                            break;
                        }
                        EditorGUILayout.EndHorizontal();

                        EditorGUILayout.BeginVertical();
                        conditionEditors[i].OnInspectorGUI();
                        EditorGUILayout.EndVertical();
                    }

                    EditorGUILayout.EndVertical();
                }
            }

            if (GUILayout.Button(new GUIContent("Add Condition", "Add a new condition to the list"), EditorStyles.miniButton))
            {
                var menu = new GenericMenu();
                for (var i = 0; i < classDetails.Count; i++)
                {
                    var conditionType = classDetails[i].ClassType;
                    menu.AddItem(new GUIContent(classDetails[i].Path), false, () => {
                        AddCondition(conditionType, conditionsProperty, serializedObject);
                    });
                }
                menu.ShowAsContext();
            }
        }
Ejemplo n.º 22
0
        private void DrawMoreButton(AssetIssueRecord record)
        {
            if (!UIHelpers.RecordButton(record, "Shows menu with additional actions for this record.", CSIcons.More))
            {
                return;
            }

            var menu = new GenericMenu();

            if (!string.IsNullOrEmpty(record.Path))
            {
                menu.AddItem(new GUIContent("Ignore/Full Path"), false, () =>
                {
                    if (!CSFilterTools.IsValueMatchesAnyFilter(record.Path, MaintainerSettings.Issues.pathIgnoresFilters))
                    {
                        var newFilter = FilterItem.Create(record.Path, FilterKind.Path);
                        ArrayUtility.Add(ref MaintainerSettings.Issues.pathIgnoresFilters, newFilter);

                        ApplyNewIgnoreFilter(newFilter);

                        MaintainerWindow.ShowNotification("Ignore added: " + record.Path);
                        CleanerFiltersWindow.Refresh();
                    }
                    else
                    {
                        MaintainerWindow.ShowNotification("Already added to the ignores!");
                    }
                });

                var dir = Directory.GetParent(record.Path);
                if (!CSPathTools.IsAssetsRootPath(dir.FullName))
                {
                    menu.AddItem(new GUIContent("Ignore/Parent Folder"), false, () =>
                    {
                        var dirPath = CSPathTools.EnforceSlashes(dir.ToString());

                        if (!CSFilterTools.IsValueMatchesAnyFilter(dirPath, MaintainerSettings.Issues.pathIgnoresFilters))
                        {
                            var newFilter = FilterItem.Create(dirPath, FilterKind.Directory);
                            ArrayUtility.Add(ref MaintainerSettings.Issues.pathIgnoresFilters, newFilter);

                            ApplyNewIgnoreFilter(newFilter);

                            MaintainerWindow.ShowNotification("Ignore added: " + dirPath);
                            CleanerFiltersWindow.Refresh();
                        }
                        else
                        {
                            MaintainerWindow.ShowNotification("Already added to the ignores!");
                        }
                    });
                }
            }

            var objectIssue = record as GameObjectIssueRecord;

            if (objectIssue != null)
            {
                if (!string.IsNullOrEmpty(objectIssue.componentName))
                {
                    menu.AddItem(new GUIContent("Ignore/\"" + objectIssue.componentName + "\" Component"), false, () =>
                    {
                        if (!CSFilterTools.IsValueMatchesAnyFilter(objectIssue.componentName, MaintainerSettings.Issues.componentIgnoresFilters))
                        {
                            var newFilter = FilterItem.Create(objectIssue.componentName, FilterKind.Type);
                            ArrayUtility.Add(ref MaintainerSettings.Issues.componentIgnoresFilters, newFilter);

                            ApplyNewIgnoreFilter(newFilter);

                            MaintainerWindow.ShowNotification("Ignore added: " + objectIssue.componentName);
                            CleanerFiltersWindow.Refresh();
                        }
                        else
                        {
                            MaintainerWindow.ShowNotification("Already added to the ignores!");
                        }
                    });
                }
            }


            menu.ShowAsContext();
        }
Ejemplo n.º 23
0
        //This is called outside Begin/End Windows from GraphEditor.
        public static void ShowToolbar(Graph graph)
        {
            var owner = graph.agent != null && graph.agent is GraphOwner && (graph.agent as GraphOwner).graph == graph ? (GraphOwner)graph.agent : null;

            GUILayout.BeginHorizontal(EditorStyles.toolbar);
            GUI.backgroundColor = Color.white.WithAlpha(0.5f);

            ///----------------------------------------------------------------------------------------------
            ///Left side
            ///----------------------------------------------------------------------------------------------

            if (GUILayout.Button("File", EditorStyles.toolbarDropDown, GUILayout.Width(50)))
            {
                GetToolbarMenu_File(graph, owner).ShowAsContext();
            }

            if (GUILayout.Button("Edit", EditorStyles.toolbarDropDown, GUILayout.Width(50)))
            {
                GetToolbarMenu_Edit(graph, owner).ShowAsContext();
            }

            if (GUILayout.Button("Prefs", EditorStyles.toolbarDropDown, GUILayout.Width(50)))
            {
                GetToolbarMenu_Prefs(graph, owner).ShowAsContext();
            }

            // var customMenu = GetToolbarMenu_Custom(graph, owner);
            // if ( customMenu.GetItemCount() > 0 ) {
            //     if ( GUILayout.Button("More", EditorStyles.toolbarDropDown, GUILayout.Width(50)) ) {
            //         customMenu.ShowAsContext();
            //     }
            // }

            GUILayout.Space(10);

            if (owner != null && GUILayout.Button("Select Owner", EditorStyles.toolbarButton, GUILayout.Width(80)))
            {
                Selection.activeObject = owner;
                EditorGUIUtility.PingObject(owner);
            }

            if (EditorUtility.IsPersistent(graph) && GUILayout.Button("Select Graph", EditorStyles.toolbarButton, GUILayout.Width(80)))
            {
                Selection.activeObject = graph;
                EditorGUIUtility.PingObject(graph);
            }

            GUILayout.Space(10);

            if (GUILayout.Button(new GUIContent(StyleSheet.log, "Open Graph Console"), EditorStyles.toolbarButton, GUILayout.MaxHeight(12)))
            {
                GraphConsole.ShowWindow();
            }

            if (GUILayout.Button(new GUIContent(StyleSheet.lens, "Open Graph Finder"), EditorStyles.toolbarButton, GUILayout.MaxHeight(12)))
            {
                GraphFinder.ShowWindow();
            }

            GUILayout.Space(10);

            ///----------------------------------------------------------------------------------------------

            graph.CallbackOnGraphEditorToolbar();

            ///----------------------------------------------------------------------------------------------
            ///Mid
            ///----------------------------------------------------------------------------------------------

            GUILayout.Space(10);
            GUILayout.FlexibleSpace();

            //...

            //...

            GUILayout.FlexibleSpace();
            GUILayout.Space(10);

            ///----------------------------------------------------------------------------------------------
            ///Right side
            ///----------------------------------------------------------------------------------------------

            GUI.backgroundColor = Color.clear;
            GUI.color           = new Color(1, 1, 1, 0.3f);
            GUILayout.Label(string.Format("{0} @NodeCanvas Framework v{1}", graph.GetType().Name, NodeCanvas.Framework.Internal.GraphSerializationData.FRAMEWORK_VERSION), EditorStyles.toolbarButton);
            GUILayout.Space(10);
            GUI.color           = Color.white;
            GUI.backgroundColor = Color.white;

            //GRAPHOWNER JUMP SELECTION
            if (owner != null)
            {
                if (GUILayout.Button(string.Format("[{0}]", owner.gameObject.name), EditorStyles.toolbarDropDown, GUILayout.Width(120)))
                {
                    var menu = new GenericMenu();
                    foreach (var _o in Object.FindObjectsOfType <GraphOwner>().OrderBy(x => x.gameObject != owner.gameObject))
                    {
                        var o = _o;
                        menu.AddItem(new GUIContent(o.gameObject.name + "/" + o.GetType().Name), o == owner, () => { SetReferences(o); });
                    }
                    menu.ShowAsContext();
                }
            }

            Prefs.isEditorLocked = GUILayout.Toggle(Prefs.isEditorLocked, "Lock", EditorStyles.toolbarButton);
            GUILayout.EndHorizontal();
            GUI.backgroundColor = Color.white;
            GUI.color           = Color.white;
        }
Ejemplo n.º 24
0
        //Returns single node context menu
        static GenericMenu GetNodeMenu_Single(Node node)
        {
            var menu = new GenericMenu();

            if (node.graph.primeNode != node && node.allowAsPrime)
            {
                menu.AddItem(new GUIContent("Set Start"), false, () => { node.graph.primeNode = node; });
            }

            if (node is IGraphAssignable)
            {
                menu.AddItem(new GUIContent("Edit Nested (Double Click)"), false, () => { node.graph.currentChildGraph = (node as IGraphAssignable).nestedGraph; });
            }

            menu.AddItem(new GUIContent("Duplicate (CTRL+D)"), false, () => { GraphEditorUtility.activeElement = node.Duplicate(node.graph); });
            menu.AddItem(new GUIContent("Copy Node"), false, () => { CopyBuffer.Set <Node[]>(new Node[] { node }); });

            if (node.inConnections.Count > 0)
            {
                menu.AddItem(new GUIContent(node.isActive? "Disable" : "Enable"), false, () => { node.SetActive(!node.isActive); });
            }

            if (node.graph.autoSort && node.outConnections.Count > 0)
            {
                menu.AddItem(new GUIContent(node.collapsed? "Expand Children" : "Collapse Children"), false, () => { node.collapsed = !node.collapsed; });
            }

            if (node is ITaskAssignable)
            {
                var assignable = node as ITaskAssignable;
                if (assignable.task != null)
                {
                    menu.AddItem(new GUIContent("Copy Assigned Task"), false, () => { CopyBuffer.Set <Task>(assignable.task); });
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Copy Assigned Task"));
                }

                if (CopyBuffer.Has <Task>())
                {
                    menu.AddItem(new GUIContent("Paste Assigned Task"), false, () =>
                    {
                        if (assignable.task == CopyBuffer.Peek <Task>())
                        {
                            return;
                        }

                        if (assignable.task != null)
                        {
                            if (!EditorUtility.DisplayDialog("Paste Task", string.Format("Node already has a Task assigned '{0}'. Replace assigned task with pasted task '{1}'?", assignable.task.name, CopyBuffer.Peek <Task>().name), "YES", "NO"))
                            {
                                return;
                            }
                        }

                        try { assignable.task = CopyBuffer.Get <Task>().Duplicate(node.graph); }
                        catch { ParadoxNotion.Services.Logger.LogWarning("Can't paste Task here. Incombatible Types", "Editor", node); }
                    });
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Paste Assigned Task"));
                }
            }

            menu = node.OnContextMenu(menu);
            if (menu != null)
            {
                menu.AddSeparator("/");
                menu.AddItem(new GUIContent("Delete (DEL)"), false, () => { node.graph.RemoveNode(node); });
            }
            return(menu);
        }
        private void DrawColumn(Rect rect, IPropertyValueEntry <TArray> entry, Context context, int columnIndex)
        {
            if (columnIndex < context.ColCount)
            {
                GUI.Label(rect, columnIndex.ToString(), SirenixGUIStyles.LabelCentered);

                // Handle Column dragging.
                if (!context.Attribute.IsReadOnly)
                {
                    var id = GUIUtility.GetControlID(FocusType.Passive);
                    if (GUI.enabled && Event.current.type == EventType.MouseDown && Event.current.button == 0 && rect.Contains(Event.current.mousePosition))
                    {
                        GUIHelper.RemoveFocusControl();
                        GUIUtility.hotControl = id;
                        EditorGUIUtility.SetWantsMouseJumping(1);
                        Event.current.Use();
                        context.ColumnDragFrom = columnIndex;
                        context.ColumnDragTo   = columnIndex;
                        context.dragStartPos   = Event.current.mousePosition;
                    }
                    else if (GUIUtility.hotControl == id)
                    {
                        if ((context.dragStartPos - Event.current.mousePosition).sqrMagnitude > 5 * 5)
                        {
                            context.IsDraggingColumn = true;
                        }
                        if (Event.current.type == EventType.MouseDrag)
                        {
                            Event.current.Use();
                        }
                        else if (Event.current.type == EventType.MouseUp)
                        {
                            GUIUtility.hotControl = 0;
                            EditorGUIUtility.SetWantsMouseJumping(0);
                            Event.current.Use();
                            context.IsDraggingColumn = false;

                            if (context.Attribute.Transpose)
                            {
                                ApplyArrayModifications(entry, arr => MultiDimArrayUtilities.MoveRow(arr, context.ColumnDragFrom, context.ColumnDragTo));
                            }
                            else
                            {
                                ApplyArrayModifications(entry, arr => MultiDimArrayUtilities.MoveColumn(arr, context.ColumnDragFrom, context.ColumnDragTo));
                            }
                        }
                    }

                    if (context.IsDraggingColumn && Event.current.type == EventType.Repaint)
                    {
                        float mouseX = Event.current.mousePosition.x;
                        if (mouseX > rect.x - 1 && mouseX < rect.x + rect.width + 1)
                        {
                            Rect arrowRect;
                            if (mouseX > rect.x + rect.width * 0.5f)
                            {
                                arrowRect            = rect.AlignRight(16);
                                arrowRect.height     = 16;
                                arrowRect.y         -= 13;
                                arrowRect.x         += 8;
                                context.ColumnDragTo = columnIndex;
                            }
                            else
                            {
                                arrowRect            = rect.AlignLeft(16);
                                arrowRect.height     = 16;
                                arrowRect.y         -= 13;
                                arrowRect.x         -= 8;
                                context.ColumnDragTo = columnIndex - 1;
                            }

                            entry.Property.Tree.DelayActionUntilRepaint(() =>
                            {
                                //GL.sRGBWrite = QualitySettings.activeColorSpace == ColorSpace.Linear;
                                GUI.DrawTexture(arrowRect, EditorIcons.ArrowDown.Active);
                                //GL.sRGBWrite = false;

                                var lineRect   = arrowRect;
                                lineRect.x     = lineRect.center.x - 2 + 1;
                                lineRect.width = 3;
                                lineRect.y    += 14;
                                lineRect.yMax  = context.Table.TableRect.yMax;
                                EditorGUI.DrawRect(lineRect, new Color(0, 0, 0, 0.6f));
                            });
                        }

                        if (columnIndex == context.ColCount - 1)
                        {
                            entry.Property.Tree.DelayActionUntilRepaint(() =>
                            {
                                var cell     = context.Table[context.Table.ColumnCount - context.ColCount + context.ColumnDragFrom, context.Table.RowCount - 1];
                                var rowRect  = cell.Rect;
                                rowRect.yMin = rect.yMin;
                                SirenixEditorGUI.DrawSolidRect(rowRect, new Color(0, 0, 0, 0.2f));
                            });
                        }
                    }
                }
            }
            else
            {
                GUI.Label(rect, "-", EditorStyles.centeredGreyMiniLabel);
            }

            if (!context.Attribute.IsReadOnly && Event.current.type == EventType.MouseDown && Event.current.button == 1 && rect.Contains(Event.current.mousePosition))
            {
                Event.current.Use();
                GenericMenu menu = new GenericMenu();
                menu.AddItem(new GUIContent("Insert 1 left"), false, () => ApplyArrayModifications(entry, arr => this.TableMatrixAttribute.Transpose ? MultiDimArrayUtilities.InsertOneRowAbove(arr, columnIndex) : MultiDimArrayUtilities.InsertOneColumnLeft(arr, columnIndex)));
                menu.AddItem(new GUIContent("Insert 1 right"), false, () => ApplyArrayModifications(entry, arr => this.TableMatrixAttribute.Transpose ? MultiDimArrayUtilities.InsertOneRowBelow(arr, columnIndex) : MultiDimArrayUtilities.InsertOneColumnRight(arr, columnIndex)));
                menu.AddItem(new GUIContent("Duplicate"), false, () => ApplyArrayModifications(entry, arr => this.TableMatrixAttribute.Transpose ? MultiDimArrayUtilities.DuplicateRow(arr, columnIndex) : MultiDimArrayUtilities.DuplicateColumn(arr, columnIndex)));
                menu.AddSeparator("");
                menu.AddItem(new GUIContent("Delete"), false, () => ApplyArrayModifications(entry, arr => this.TableMatrixAttribute.Transpose ? MultiDimArrayUtilities.DeleteRow(arr, columnIndex) : MultiDimArrayUtilities.DeleteColumn(arr, columnIndex)));
                menu.ShowAsContext();
            }
        }
 public virtual void AddItemsToMenu(GenericMenu menu)
 {
     //menu.AddSeparator(string.Empty);
     menu.AddItem(new GUIContent("Custom Sources"), multiDataSource, FlipDataSource);
 }
Ejemplo n.º 27
0
        private void AddContextMenuLoggedMessages(GenericMenu menu, string listName, string messageActorPrefix, Dictionary <Type, List <LoggedMessage> > logs)
        {
            if (logs.Count == 0)
            {
                menu.AddDisabledItem(new GUIContent(listName));
                return;
            }

            const string typelessMessagesName = "Typeless Messages";

            foreach (KeyValuePair <Type, List <LoggedMessage> > pair in logs)
            {
                bool   isTypeless = pair.Key == typeof(Message);
                string typeName   = isTypeless ? typelessMessagesName : pair.Key.ToString();

                // Check if there is no nameless message of a typed message
                if (!isTypeless)
                {
                    menu.AddItem(new GUIContent(listName + "/" + typeName + "/Open " + typeName + ".cs"), false, delegate() {
                        CodeControlEditorHelper.OpenCodeOfType(pair.Key);
                    });
                    menu.AddSeparator(listName + "/" + typeName + "/");
                }

                // Make sure the nameless message shows first
                List <LoggedMessage> sortedLogMessages = new List <LoggedMessage>();
                LoggedMessage        namelessMessage   = pair.Value.Find(x => x.MessageName == "");
                if (namelessMessage != null)
                {
                    sortedLogMessages.Add(namelessMessage);
                }
                sortedLogMessages.AddList <LoggedMessage>(pair.Value.FindAll(x => x.MessageName != ""));

                int messageIndex = 0;
                foreach (LoggedMessage logMessage in sortedLogMessages)
                {
                    // If this message is nameless, show title as nameless
                    if (logMessage.MessageName == "")
                    {
                        menu.AddDisabledItem(new GUIContent(listName + "/" + typeName + "/Nameless Message"));
                    }
                    else
                    {
                        menu.AddDisabledItem(new GUIContent(listName + "/" + typeName + "/" + '"' + logMessage.MessageName + '"'));
                    }

                    foreach (MessageActorWidget actor in logMessage.AssociatedActors)
                    {
                        string itemName = messageActorPrefix + actor.ActorTypeName + ".cs";

                        // Add blank spaces as postfix to force the ContextMenu to show these items more than once
                        for (int i = 0; i < messageIndex; i++)
                        {
                            itemName += ' ';
                        }

                        menu.AddItem(new GUIContent(listName + "/" + typeName + "/" + itemName), false, delegate() {
                            CodeControlEditorHelper.OpenCodeOfType(actor.ActorType);
                        });
                    }

                    if (pair.Value.IndexOf(logMessage) < pair.Value.Count - 1)
                    {
                        menu.AddSeparator(listName + "/" + typeName + "/");
                    }

                    messageIndex++;
                }
            }
        }
        void ModeToggle()
        {
            GUILayout.BeginHorizontal();
            GUILayout.Space(k_ToolbarPadding);
            if (m_Mode == Mode.Browser)
            {
                bool clicked = GUILayout.Button(m_RefreshTexture);
                if (clicked)
                {
                    m_ManageTab.ForceReloadData();
                }
            }
            else
            {
                GUILayout.Space(m_RefreshTexture.width + k_ToolbarPadding);
            }
            float toolbarWidth = position.width - k_ToolbarPadding * 4 - m_RefreshTexture.width;

            string[] labels = new string[2] {
                "Configure", "Build"
            };                                                       //, "Inspect" };
            m_Mode = (Mode)GUILayout.Toolbar((int)m_Mode, labels, "LargeButton", GUILayout.Width(toolbarWidth));
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            if (multiDataSource)
            {
                //GUILayout.BeginArea(r);
                GUILayout.BeginHorizontal();

                using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
                {
                    GUILayout.Label("Bundle Data Source:");
                    GUILayout.FlexibleSpace();
                    var c = new GUIContent(string.Format("{0} ({1})", AssetBundleModel.Model.DataSource.Name, AssetBundleModel.Model.DataSource.ProviderName), "Select Asset Bundle Set");
                    if (GUILayout.Button(c, EditorStyles.toolbarPopup))
                    {
                        GenericMenu menu      = new GenericMenu();
                        bool        firstItem = true;

                        foreach (var info in AssetBundleDataSource.ABDataSourceProviderUtility.CustomABDataSourceTypes)
                        {
                            List <AssetBundleDataSource.ABDataSource> dataSourceList = null;
                            dataSourceList = info.GetMethod("CreateDataSources").Invoke(null, null) as List <AssetBundleDataSource.ABDataSource>;


                            if (dataSourceList == null)
                            {
                                continue;
                            }

                            if (!firstItem)
                            {
                                menu.AddSeparator("");
                            }

                            foreach (var ds in dataSourceList)
                            {
                                menu.AddItem(new GUIContent(string.Format("{0} ({1})", ds.Name, ds.ProviderName)), false,
                                             () =>
                                {
                                    var thisDataSource = ds;
                                    AssetBundleModel.Model.DataSource = thisDataSource;
                                    m_ManageTab.ForceReloadData();
                                }
                                             );
                            }

                            firstItem = false;
                        }

                        menu.ShowAsContext();
                    }

                    GUILayout.FlexibleSpace();
                    if (AssetBundleModel.Model.DataSource.IsReadOnly())
                    {
                        GUIStyle tbLabel = new GUIStyle(EditorStyles.toolbar);
                        tbLabel.alignment = TextAnchor.MiddleRight;

                        GUILayout.Label("Read Only", tbLabel);
                    }
                }

                GUILayout.EndHorizontal();
                //GUILayout.EndArea();
            }
        }
Ejemplo n.º 29
0
        public override void OnInspectorGUI()
        {
            GUILayout.BeginHorizontal();
            EditorGUILayout.HelpBox("HTFramework Main Module!", MessageType.Info);
            GUILayout.EndHorizontal();

            #region MainData
            GUILayout.BeginVertical("Box");

            GUILayout.BeginHorizontal();
            GUILayout.Label("MainData");
            if (GUILayout.Button(_target.MainDataType, "MiniPopup"))
            {
                GenericMenu gm    = new GenericMenu();
                List <Type> types = GlobalTools.GetTypesInRunTimeAssemblies();
                gm.AddItem(new GUIContent("<None>"), _target.MainDataType == "<None>", () =>
                {
                    Undo.RecordObject(target, "Set Main Data");
                    _target.MainDataType = "<None>";
                    this.HasChanged();
                });
                for (int i = 0; i < types.Count; i++)
                {
                    if (types[i].BaseType == typeof(MainData))
                    {
                        int j = i;
                        gm.AddItem(new GUIContent(types[j].FullName), _target.MainDataType == types[j].FullName, () =>
                        {
                            Undo.RecordObject(target, "Set Main Data");
                            _target.MainDataType = types[j].FullName;
                            this.HasChanged();
                        });
                    }
                }
                gm.ShowAsContext();
            }
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();
            #endregion

            #region License
            GUILayout.BeginVertical("Box");

            GUILayout.BeginHorizontal();
            this.Toggle(_target.IsPermanentLicense, out _target.IsPermanentLicense, "Permanent License");
            GUILayout.EndHorizontal();

            if (!_target.IsPermanentLicense)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Prompt:", "BoldLabel");
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                this.TextField(_target.EndingPrompt, out _target.EndingPrompt);
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Ending Time:", "BoldLabel");
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Year:", GUILayout.Width(45));
                int year = EditorGUILayout.IntField(_target.Year, GUILayout.Width(50));
                if (year != _target.Year)
                {
                    Undo.RecordObject(target, "Set Year");
                    _target.Year = year;
                    CorrectDateTime();
                    this.HasChanged();
                }
                if (GUILayout.Button("", "OL Plus", GUILayout.Width(15)))
                {
                    Undo.RecordObject(target, "Set Year");
                    _target.Year += 1;
                    CorrectDateTime();
                    this.HasChanged();
                }
                if (GUILayout.Button("", "OL Minus", GUILayout.Width(15)))
                {
                    Undo.RecordObject(target, "Set Year");
                    _target.Year -= 1;
                    CorrectDateTime();
                    this.HasChanged();
                }
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Month:", GUILayout.Width(45));
                int month = EditorGUILayout.IntField(_target.Month, GUILayout.Width(50));
                if (month != _target.Month)
                {
                    Undo.RecordObject(target, "Set Month");
                    _target.Month = month;
                    CorrectDateTime();
                    this.HasChanged();
                }
                if (GUILayout.Button("", "OL Plus", GUILayout.Width(15)))
                {
                    Undo.RecordObject(target, "Set Month");
                    _target.Month += 1;
                    CorrectDateTime();
                    this.HasChanged();
                }
                if (GUILayout.Button("", "OL Minus", GUILayout.Width(15)))
                {
                    Undo.RecordObject(target, "Set Month");
                    _target.Month -= 1;
                    CorrectDateTime();
                    this.HasChanged();
                }
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Day:", GUILayout.Width(45));
                int day = EditorGUILayout.IntField(_target.Day, GUILayout.Width(50));
                if (day != _target.Day)
                {
                    Undo.RecordObject(target, "Set Day");
                    _target.Day = day;
                    CorrectDateTime();
                    this.HasChanged();
                }
                if (GUILayout.Button("", "OL Plus", GUILayout.Width(15)))
                {
                    Undo.RecordObject(target, "Set Day");
                    _target.Day += 1;
                    CorrectDateTime();
                    this.HasChanged();
                }
                if (GUILayout.Button("", "OL Minus", GUILayout.Width(15)))
                {
                    Undo.RecordObject(target, "Set Day");
                    _target.Day -= 1;
                    CorrectDateTime();
                    this.HasChanged();
                }
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                if (GUILayout.Button("Now", "MiniButton"))
                {
                    Undo.RecordObject(target, "Set Now");
                    _target.Year  = DateTime.Now.Year;
                    _target.Month = DateTime.Now.Month;
                    _target.Day   = DateTime.Now.Day;
                    CorrectDateTime();
                    this.HasChanged();
                }
                if (GUILayout.Button("2 Months Later", "MiniButton"))
                {
                    Undo.RecordObject(target, "Set 2 Months Later");
                    _target.Month += 2;
                    CorrectDateTime();
                    this.HasChanged();
                }
                GUILayout.EndHorizontal();
            }

            GUILayout.EndVertical();
            #endregion
        }
Ejemplo n.º 30
0
        protected override void OnInspectorDefaultGUI()
        {
            base.OnInspectorDefaultGUI();

            GUILayout.BeginVertical(EditorGlobalTools.Styles.Box);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Define Entity:");
            GUILayout.EndHorizontal();

            for (int i = 0; i < Target.DefineEntityNames.Count; i++)
            {
                GUILayout.BeginVertical(EditorStyles.helpBox);

                GUILayout.BeginHorizontal();
                GUILayout.Label("Type", GUILayout.Width(40));
                if (GUILayout.Button(Target.DefineEntityNames[i], EditorGlobalTools.Styles.MiniPopup))
                {
                    GenericMenu gm    = new GenericMenu();
                    List <Type> types = ReflectionToolkit.GetTypesInRunTimeAssemblies(type =>
                    {
                        return(type.IsSubclassOf(typeof(EntityLogicBase)));
                    });
                    for (int m = 0; m < types.Count; m++)
                    {
                        int j = i;
                        int n = m;
                        if (Target.DefineEntityNames.Contains(types[n].FullName))
                        {
                            gm.AddDisabledItem(new GUIContent(types[n].FullName));
                        }
                        else
                        {
                            gm.AddItem(new GUIContent(types[n].FullName), Target.DefineEntityNames[j] == types[n].FullName, () =>
                            {
                                Undo.RecordObject(target, "Set Define Entity Name");
                                Target.DefineEntityNames[j] = types[n].FullName;
                                HasChanged();
                            });
                        }
                    }
                    gm.ShowAsContext();
                }
                GUI.backgroundColor = Color.red;
                if (GUILayout.Button("Delete", EditorStyles.miniButton, GUILayout.Width(50)))
                {
                    Undo.RecordObject(target, "Delete Define Entity");
                    Target.DefineEntityNames.RemoveAt(i);
                    Target.DefineEntityTargets.RemoveAt(i);
                    HasChanged();
                    continue;
                }
                GUI.backgroundColor = Color.white;
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Entity", GUILayout.Width(40));
                GameObject entity = Target.DefineEntityTargets[i];
                ObjectField(Target.DefineEntityTargets[i], out entity, false, "");
                if (entity != Target.DefineEntityTargets[i])
                {
                    Target.DefineEntityTargets[i] = entity;
                }
                GUILayout.EndHorizontal();

                GUILayout.EndVertical();
            }

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("New", EditorStyles.miniButton))
            {
                Undo.RecordObject(target, "New Define Entity");
                Target.DefineEntityNames.Add("<None>");
                Target.DefineEntityTargets.Add(null);
                HasChanged();
            }
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();
        }
Ejemplo n.º 31
0
    void MethodSelector(SerializedProperty property)
    {
        // Return type constraint
        Type returnType = null;

        // Arg type constraint
        Type[] argTypes = new Type[0];

        // Get return type and argument constraints
        SerializableCallbackBase dummy = GetDummyFunction(property);

        Type[] genericTypes = dummy.GetType().BaseType.GetGenericArguments();
        // SerializableEventBase is always void return type
        if (dummy is SerializableEventBase)
        {
            returnType = typeof(void);
            if (genericTypes.Length > 0)
            {
                argTypes = new Type[genericTypes.Length];
                Array.Copy(genericTypes, argTypes, genericTypes.Length);
            }
        }
        else
        {
            if (genericTypes != null && genericTypes.Length > 0)
            {
                // The last generic argument is the return type
                returnType = genericTypes[genericTypes.Length - 1];
                if (genericTypes.Length > 1)
                {
                    argTypes = new Type[genericTypes.Length - 1];
                    Array.Copy(genericTypes, argTypes, genericTypes.Length - 1);
                }
            }
        }

        SerializedProperty targetProp = property.FindPropertyRelative("_target");

        List <MenuItem> dynamicItems = new List <MenuItem>();
        List <MenuItem> staticItems  = new List <MenuItem>();

        List <Object> targets = new List <Object>()
        {
            targetProp.objectReferenceValue
        };

        if (targets[0] is Component)
        {
            targets = (targets[0] as Component).gameObject.GetComponents <Component>().ToList <Object>();
            targets.Add((targetProp.objectReferenceValue as Component).gameObject);
        }
        else if (targets[0] is GameObject)
        {
            targets = (targets[0] as GameObject).GetComponents <Component>().ToList <Object>();
            targets.Add(targetProp.objectReferenceValue as GameObject);
        }
        for (int c = 0; c < targets.Count; c++)
        {
            Object       t       = targets[c];
            MethodInfo[] methods = targets[c].GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

            for (int i = 0; i < methods.Length; i++)
            {
                MethodInfo method = methods[i];

                // Skip methods with wrong return type
                if (returnType != null && method.ReturnType != returnType)
                {
                    continue;
                }
                // Skip methods with null return type
                // if (method.ReturnType == typeof(void)) continue;
                // Skip generic methods
                if (method.IsGenericMethod)
                {
                    continue;
                }

                Type[] parms = method.GetParameters().Select(x => x.ParameterType).ToArray();

                // Skip methods with more than 4 args
                if (parms.Length > 4)
                {
                    continue;
                }
                // Skip methods with unsupported args
                if (parms.Any(x => !Arg.IsSupported(x)))
                {
                    continue;
                }

                string methodPrettyName = PrettifyMethod(methods[i]);
                staticItems.Add(new MenuItem(targets[c].GetType().Name + "/" + methods[i].DeclaringType.Name, methodPrettyName, () => SetMethod(property, t, method, false)));

                // Skip methods with wrong constrained args
                if (argTypes.Length == 0 || !Enumerable.SequenceEqual(argTypes, parms))
                {
                    continue;
                }

                dynamicItems.Add(new MenuItem(targets[c].GetType().Name + "/" + methods[i].DeclaringType.Name, methods[i].Name, () => SetMethod(property, t, method, true)));
            }
        }

        // Construct and display context menu
        GenericMenu menu = new GenericMenu();

        if (dynamicItems.Count > 0)
        {
            string[] paths = dynamicItems.GroupBy(x => x.path).Select(x => x.First().path).ToArray();
            foreach (string path in paths)
            {
                menu.AddItem(new GUIContent(path + "/Dynamic " + PrettifyTypes(argTypes)), false, null);
            }
            for (int i = 0; i < dynamicItems.Count; i++)
            {
                menu.AddItem(dynamicItems[i].label, false, dynamicItems[i].action);
            }
            foreach (string path in paths)
            {
                menu.AddItem(new GUIContent(path + "/  "), false, null);
                menu.AddItem(new GUIContent(path + "/Static parameters"), false, null);
            }
        }
        for (int i = 0; i < staticItems.Count; i++)
        {
            menu.AddItem(staticItems[i].label, false, staticItems[i].action);
        }
        if (menu.GetItemCount() == 0)
        {
            menu.AddDisabledItem(new GUIContent("No methods with return type '" + GetTypeName(returnType) + "'"));
        }
        menu.ShowAsContext();
    }
Ejemplo n.º 32
0
    //Context menu used for dialogue, node, and element control/commands
    void ProcessContextMenu(Event e, bool showStart)
    {
        GenericMenu menu = new GenericMenu();

        if (tempNode != null)
        {
            if (tempNode.nodeID != 0)
            {
                if (tempElement != null)
                {
                    menu.AddItem(new GUIContent("Delete " + tempElement.GetType().ToString()), false, ContextCallBack, "7");
                    menu.AddItem(new GUIContent("Duplicate " + tempElement.GetType().ToString()), false, ContextCallBack, "8");
                    menu.AddSeparator("");
                }
                menu.AddItem(new GUIContent("Add Line"), false, ContextCallBack, "0");
                menu.AddItem(new GUIContent("Add Option"), false, ContextCallBack, "1");
                menu.AddItem(new GUIContent("Add Redirection"), false, ContextCallBack, "2");
                menu.AddItem(new GUIContent("Add Action"), false, ContextCallBack, "3");
                menu.AddSeparator("");
            }
            menu.AddItem(new GUIContent("Move to Back"), false, ContextCallBack, "9");
            menu.AddItem(new GUIContent("Move to Front"), false, ContextCallBack, "10");
            menu.AddItem(new GUIContent("Delete Node"), false, ContextCallBack, "6");
        }
        else
        {
            menu.AddItem(new GUIContent("Create Node"), false, ContextCallBack, "5");
            if (showStart)
            {
                menu.AddItem(new GUIContent("Create Start Node"), false, ContextCallBack, "4");
            }
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("Save Dialogue"), false, ContextCallBack, "11");
            menu.AddItem(new GUIContent("Load Dialogue"), false, ContextCallBack, "12");
        }
        menu.ShowAsContext();
        e.Use();
    }
Ejemplo n.º 33
0
    private void OnEnable()
    {
        // create a list out of a List<Waves>
        list = new ReorderableList(serializedObject,
                                   serializedObject.FindProperty("Waves"),
                                   true, true, true, true);

        // define elements in the list
        list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
        {
            var element = list.serializedProperty.GetArrayElementAtIndex(index);
            rect.y += 2;
            EditorGUI.PropertyField(
                new Rect(rect.x, rect.y, 60, EditorGUIUtility.singleLineHeight),
                element.FindPropertyRelative("Type"), GUIContent.none);
            EditorGUI.PropertyField(
                new Rect(rect.x + 60, rect.y, rect.width - 60 - 30, EditorGUIUtility.singleLineHeight),
                element.FindPropertyRelative("Prefab"), GUIContent.none);
            EditorGUI.PropertyField(
                new Rect(rect.x + rect.width - 30, rect.y, 30, EditorGUIUtility.singleLineHeight),
                element.FindPropertyRelative("Count"), GUIContent.none);
        };

        list.drawHeaderCallback = (Rect rect) =>
        {
            EditorGUI.LabelField(rect, "Monster Waves");
        };

        list.onSelectCallback = (ReorderableList l) =>
        {
            var prefab = l.serializedProperty.GetArrayElementAtIndex(l.index).FindPropertyRelative("Prefab").objectReferenceValue as GameObject;
            if (prefab)
            {
                EditorGUIUtility.PingObject(prefab.gameObject);
            }
        };

        list.onCanRemoveCallback = (ReorderableList l) =>
        {
            return(l.count > 1);
        };

        list.onRemoveCallback = (ReorderableList l) =>
        {
            if (EditorUtility.DisplayDialog("Warning!",
                                            "Are you sure you want to delete the wave?", "Yes", "No"))
            {
                ReorderableList.defaultBehaviours.DoRemoveButton(l);
            }
        };

        list.onAddCallback = (ReorderableList l) =>
        {
            var index = l.serializedProperty.arraySize;
            l.serializedProperty.arraySize++;
            l.index = index;
            var element = l.serializedProperty.GetArrayElementAtIndex(index);
            element.FindPropertyRelative("Type").enumValueIndex         = 0;
            element.FindPropertyRelative("Count").intValue              = 20;
            element.FindPropertyRelative("Prefab").objectReferenceValue =
                AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Mobs/Cube.prefab",
                                              typeof(GameObject)) as GameObject;
        };

        list.onAddDropdownCallback = (Rect buttonRect, ReorderableList l) =>
        {
            var menu  = new GenericMenu();
            var guids = AssetDatabase.FindAssets("", new[] { "Assets/Prefabs/Mobs" });
            foreach (var guid in guids)
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);
                menu.AddItem(new GUIContent("Mobs/" + Path.GetFileNameWithoutExtension(path)),
                             false, clickHandler,
                             new WaveCreationParams()
                {
                    Type = MobWave.WaveType.Mobs, Path = path
                });
            }
            guids = AssetDatabase.FindAssets("", new[] { "Assets/Prefabs/Bosses" });
            foreach (var guid in guids)
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);
                menu.AddItem(new GUIContent("Bosses/" + Path.GetFileNameWithoutExtension(path)),
                             false, clickHandler,
                             new WaveCreationParams()
                {
                    Type = MobWave.WaveType.Boss, Path = path
                });
            }
            menu.ShowAsContext();
        };
    }
Ejemplo n.º 34
0
    private void OnGUI()
    {
        switch (Event.current.type)
        {
            case EventType.KeyDown:
                if ((Event.current.modifiers & ~EventModifiers.FunctionKey) == EventModifiers.Control &&
                    (Event.current.keyCode == KeyCode.PageUp || Event.current.keyCode == KeyCode.PageDown))
                {
                    SelectAdjacentCodeTab(Event.current.keyCode == KeyCode.PageDown);
                    Event.current.Use();
                    GUIUtility.ExitGUI();
                }
                else if (Event.current.alt && EditorGUI.actionKey)
                {
                    if (Event.current.keyCode == KeyCode.RightArrow || Event.current.keyCode == KeyCode.LeftArrow)
                    {
                        if (Event.current.shift)
                        {
                            MoveThisTab(Event.current.keyCode == KeyCode.RightArrow);
                        }
                        else
                        {
                            SelectAdjacentCodeTab(Event.current.keyCode == KeyCode.RightArrow);
                        }
                        Event.current.Use();
                        GUIUtility.ExitGUI();
                    }
                }
                else if (!Event.current.alt && !Event.current.shift && EditorGUI.actionKey)
                {
                    if (Event.current.keyCode == KeyCode.W || Event.current.keyCode == KeyCode.F4)
                    {
                        Event.current.Use();
                        FGCodeWindow codeTab = GetAdjacentCodeTab(false);
                        if (codeTab == null)
                            codeTab = GetAdjacentCodeTab(true);
                        Close();
                        if (codeTab != null)
                            codeTab.Focus();
                    }
                }
                //else if (!Event.current.alt && !Event.current.shift && EditorGUI.actionKey)
                //{
                //	if (Event.current.keyCode == KeyCode.M)
                //	{
                //		Event.current.Use();
                //		ToggleMaximized();
                //		GUIUtility.ExitGUI();
                //	}
                //}
                break;

            case EventType.DragUpdated:
            case EventType.DragPerform:
                if (DragAndDrop.objectReferences.Length > 0)
                {
                    bool ask = false;

                    HashSet<Object> accepted = new HashSet<Object>();
                    foreach (Object obj in DragAndDrop.objectReferences)
                    {
                        if (AssetDatabase.GetAssetPath(obj).EndsWith(".dll", System.StringComparison.OrdinalIgnoreCase))
                            continue;

                        if (obj is MonoScript)
                            accepted.Add(obj);
                        else if (obj is TextAsset || obj is Shader)
                            accepted.Add(obj);
                        else if (obj is Material)
                        {
                            Material material = obj as Material;
                            if (material.shader != null)
                            {
                                int shaderID = material.shader.GetInstanceID();
                                if (shaderID != 0)
                                {
                                    if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(shaderID)))
                                        accepted.Add(material.shader);
                                }
                            }
                        }
                        else if (obj is GameObject)
                        {
                            GameObject gameObject = obj as GameObject;
                            MonoBehaviour[] monoBehaviours = gameObject.GetComponents<MonoBehaviour>();
                            foreach (MonoBehaviour mb in monoBehaviours)
                            {
                                MonoScript monoScript = MonoScript.FromMonoBehaviour(mb);
                                if (monoScript != null)
                                {
                                    if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(monoScript)))
                                    {
                                        accepted.Add(monoScript);
                                        ask = true;
                                    }
                                }
                            }
                        }
                    }

                    if (accepted.Count > 0)
                    {
                        DragAndDrop.AcceptDrag();
                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                        if (Event.current.type == EventType.DragPerform)
                        {
                            Object[] sorted = accepted.OrderBy((x) => x.name, System.StringComparer.OrdinalIgnoreCase).ToArray();

                            if (ask && sorted.Length > 1)
                            {
                                GenericMenu popupMenu = new GenericMenu();
                                foreach (Object target in sorted)
                                {
                                    Object tempTarget = target;
                                    popupMenu.AddItem(
                                        new GUIContent("Open " + System.IO.Path.GetFileName(AssetDatabase.GetAssetPath(target))),
                                        false,
                                        () => { OpenNewWindow(tempTarget, this, true); });
                                }
                                popupMenu.AddSeparator("");
                                popupMenu.AddItem(
                                    new GUIContent("Open All"),
                                    false,
                                    () => { foreach (Object target in sorted) OpenNewWindow(target, this); });

                                popupMenu.ShowAsContext();
                            }
                            else
                            {
                                foreach (Object target in sorted)
                                    OpenNewWindow(target, this, sorted.Length == 1);
                            }
                        }
                        Event.current.Use();
                        return;
                    }
                }
                break;

            case EventType.ValidateCommand:
                if (Event.current.commandName == "ScriptInspector.AddTab")
                {
                    Event.current.Use();
                    return;
                }
                break;

            case EventType.ExecuteCommand:
                if (Event.current.commandName == "ScriptInspector.AddTab")
                {
                    Event.current.Use();
                    OpenNewWindow(targetAsset, this);
                    return;
                }
                break;
        }

        wantsMouseMove = true;
        textEditor.OnWindowGUI(this, new RectOffset(0, 0, 19, 1));
    }
Ejemplo n.º 35
0
            private void ShowContextMenuOfValue(ChangerPlate parent, ConditionTypeValuePair typeValuePair)
            {
                var conditionType  = typeValuePair.conditionType;
                var conditionValue = typeValuePair.conditionValue;

                var menu = new GenericMenu();

                // update parent:ChangerPlate's conditions to latest.
                ChangerPlate.Emit(new OnChangerEvent(OnChangerEvent.EventType.EVENT_REFRESHCONDITIONS, parent.changerId));

                var menuItems = parent.conditions
                                .Where(data => data.conditionType == conditionType)
                                .FirstOrDefault();

                // current.
                if (!string.IsNullOrEmpty(conditionValue))
                {
                    menu.AddDisabledItem(
                        new GUIContent(conditionValue)
                        );
                    menu.AddSeparator(string.Empty);
                }

                // new.
                if (string.IsNullOrEmpty(conditionType))
                {
                    menu.AddItem(
                        new GUIContent("Add New Type & Value"),
                        false,
                        () =>
                    {
                        ChangerPlate.Emit(new OnChangerEvent(OnChangerEvent.EventType.EVENT_ADDNEWTYPEVALUE, parent.changerId));
                    }
                        );
                }
                else
                {
                    menu.AddItem(
                        new GUIContent("Add New Value"),
                        false,
                        () =>
                    {
                        ChangerPlate.Emit(new OnChangerEvent(OnChangerEvent.EventType.EVENT_ADDNEWVALUE, parent.changerId));
                    }
                        );
                }


                // show other conditionValues.
                if (menuItems != null)
                {
                    // remove current.
                    menuItems.conditionValues.Remove(conditionValue);

                    menu.AddSeparator(string.Empty);

                    // other.
                    foreach (var currentConditionValue in menuItems.conditionValues.Select((val, index) => new { index, val }))
                    {
                        // var currentType = conditionType;

                        var currentValue = currentConditionValue.val;
                        var currentIndex = currentConditionValue.index;

                        menu.AddItem(
                            new GUIContent(currentValue),
                            false,
                            () =>
                        {
                            parent.EmitUndo("Change Combination Value");
                            typeValuePair.conditionValue = menuItems.conditionValues[currentIndex];
                            parent.EmitSave();
                        }
                            );
                    }
                }

                menu.ShowAsContext();
            }
Ejemplo n.º 36
0
    private void DoPopupMenu(EditorWindow console)
    {
        var listView = consoleListViewField.GetValue(console);
        int listViewRow = listView != null ? (int) listViewStateRowField.GetValue(listView) : -1;

        if (listViewRow < 0)
            return;

        string text = (string)consoleActiveTextField.GetValue(console);
        if (string.IsNullOrEmpty(text))
            return;

        GenericMenu codeViewPopupMenu = new GenericMenu();

        string[] lines = text.Split('\n');
        foreach (string line in lines)
        {
            int atAssetsIndex = line.IndexOf("(at Assets/");
            if (atAssetsIndex < 0)
                continue;

            int functionNameEnd = line.IndexOf('(');
            if (functionNameEnd < 0)
                continue;
            string functionName = line.Substring(0, functionNameEnd).TrimEnd(' ');

            int lineIndex = line.LastIndexOf(':');
            if (lineIndex <= atAssetsIndex)
                continue;
            int atLine = 0;
            for (int i = lineIndex + 1; i < line.Length; ++i)
            {
                char c = line[i];
                if (c < '0' || c > '9')
                    break;
                atLine = atLine * 10 + (c - '0');
            }

            atAssetsIndex += "(at ".Length;
            string assetPath = line.Substring(atAssetsIndex, lineIndex - atAssetsIndex);
            string scriptName = assetPath.Substring(assetPath.LastIndexOf('/') + 1);

            string guid = AssetDatabase.AssetPathToGUID(assetPath);
            if (!string.IsNullOrEmpty(guid))
            {
                codeViewPopupMenu.AddItem(
                    new GUIContent(scriptName + " - " + functionName.Replace(':', '.') + ", line " + atLine),
                    false,
                    () => FGCodeWindow.OpenAssetInTab(guid, atLine));
            }
        }

        if (codeViewPopupMenu.GetItemCount() > 0)
            codeViewPopupMenu.ShowAsContext();
    }
Ejemplo n.º 37
0
        ///----------------------------------------------------------------------------------------------

        //PREFS MENU
        static GenericMenu GetToolbarMenu_Prefs(Graph graph, GraphOwner owner)
        {
            var menu = new GenericMenu();

            menu.AddItem(new GUIContent("Show Icons"), Prefs.showIcons, () => { Prefs.showIcons = !Prefs.showIcons; });
            menu.AddItem(new GUIContent("Show Node Help"), Prefs.showNodeInfo, () => { Prefs.showNodeInfo = !Prefs.showNodeInfo; });
            menu.AddItem(new GUIContent("Show Comments"), Prefs.showComments, () => { Prefs.showComments = !Prefs.showComments; });
            menu.AddItem(new GUIContent("Show Summary Info"), Prefs.showTaskSummary, () => { Prefs.showTaskSummary = !Prefs.showTaskSummary; });
            menu.AddItem(new GUIContent("Show Node IDs"), Prefs.showNodeIDs, () => { Prefs.showNodeIDs = !Prefs.showNodeIDs; });
            menu.AddItem(new GUIContent("Grid Snap"), Prefs.doSnap, () => { Prefs.doSnap = !Prefs.doSnap; });
            menu.AddItem(new GUIContent("Log Events"), Prefs.logEvents, () => { Prefs.logEvents = !Prefs.logEvents; });
            menu.AddItem(new GUIContent("Log Dynamic Parameters Info"), Prefs.logDynamicParametersInfo, () => { Prefs.logDynamicParametersInfo = !Prefs.logDynamicParametersInfo; });
            menu.AddItem(new GUIContent("Breakpoints Pause Editor"), Prefs.breakpointPauseEditor, () => { Prefs.breakpointPauseEditor = !Prefs.breakpointPauseEditor; });
            menu.AddItem(new GUIContent("Show Hierarchy Icons"), Prefs.showHierarchyIcons, () => { Prefs.showHierarchyIcons = !Prefs.showHierarchyIcons; });
            if (graph.isTree)
            {
                menu.AddItem(new GUIContent("Automatic Hierarchical Move"), Prefs.hierarchicalMove, () => { Prefs.hierarchicalMove = !Prefs.hierarchicalMove; });
            }
            menu.AddItem(new GUIContent("Open Preferred Types Editor..."), false, () => { TypePrefsEditorWindow.ShowWindow(); });
            return(menu);
        }
Ejemplo n.º 38
0
	void MouseListener()
	{
		// Figure out where the mouse is relative to the DecalGroup layout
		mouseOver_groupIndex = -1;
		mouseOver_textureIndex = -1;

		if(!textureDisplayRect.Contains(e.mousePosition))
			return;

		// first check hovering rect.  use this hovering struct because otherwise the gui
		// runs on/off when checking hover status (if it's over, move it, but then it's moved so 
		// it's not over, and move back... cyclical logic ftw)
		if(dragging && hovering.bounds.Contains(mousePositionInGroupRect))	
		{
			mouseOver_groupIndex = hovering.groupIndex;
			mouseOver_textureIndex = hovering.textureIndex;
		}
		else
		{
			if(textureDisplayRect.Contains(e.mousePosition))
			for(int i = 0; i < groupRects.Length; i++)
			{
				if( groupRects[i].Contains(mousePositionInGroupRect) )
				{
					mouseOver_groupIndex = i;
					for(int j = 0; j < decalRects[i].Length; j++)
					{
						if(decalRects[i][j].Contains(mousePositionInGroupRect))
							mouseOver_textureIndex = j;
					}
					break;
				}
			}
		}

		switch(Event.current.type)
		{
			case EventType.MouseDown:
				mouseOrigin = e.mousePosition;
				if(mouseOver_groupIndex > -1 && mouseOver_textureIndex > -1)
					validDrag = true;
				else
					validDrag = false;

				break;

			case EventType.MouseDrag:
				
				if(!validDrag) return;

				if(Vector2.Distance(mouseOrigin, e.mousePosition) > 7f && !dragging && mouseOver_groupIndex > -1 && mouseOver_textureIndex > -1)
				{
					dragging = true;

					dragOriginIndex = mouseOver_groupIndex;
					
					if(!selected.Contains(mouseOver_groupIndex, mouseOver_textureIndex))
					{
						selected.Clear();
						selected.Add(mouseOver_groupIndex, mouseOver_textureIndex);
					}
					
					dragTextures = new List<Texture2D>();
					dragMouseOffset = new List<Vector2>();

					foreach(KeyValuePair<int, List<int>> kvp in selected)
					{
						bool exit = false;
						foreach(int n in kvp.Value)
						{
							Rect r = decalRects[kvp.Key][n];
							dragMouseOffset.Add(new Vector2(r.x - mousePositionInGroupRect.x, r.y - mousePositionInGroupRect.y));
							dragTextures.Add(decalGroups[kvp.Key].decals[n].texture);
						}
						if(exit) break;
					}

				}
			
				if(dragging)
					Repaint();
				
				break;

			case EventType.Ignore:

				dragging = false;
				dragTextures = null;
				Repaint();
				break;

			case EventType.MouseUp:
				if(dragging)
				{
					dragTextures = null;
					List<QD.Decal> imgs = new List<QD.Decal>();
					foreach(KeyValuePair<int, List<int>> kvp in selected)
						foreach(int n in kvp.Value)
							imgs.Add( decalGroups[kvp.Key].decals[n] );
			
					// since we might remove some decals that are before the insert point,
					// this offset accounts for it and puts the new images in the right place even afeter
					// deletion
					int textureOffset = 0;
					if(selected.ContainsKey(mouseOver_groupIndex))
					{
						foreach(int n in selected[mouseOver_groupIndex])
							if(n < mouseOver_textureIndex)
								textureOffset++;
					}

					DeleteSelectedDecals();
					PerformDragDrop(imgs, mouseOver_groupIndex, mouseOver_textureIndex-textureOffset);
					PruneGroups();
				}

				if(!e.shift)
					selected.Clear();
				
				if(mouseOver_groupIndex > -1)
				{
					if(selected.ContainsKey(mouseOver_groupIndex))
					{
						if(mouseOver_textureIndex > -1)
						{
							if(!selected[mouseOver_groupIndex].Contains(mouseOver_textureIndex))
								selected[mouseOver_groupIndex].Add(mouseOver_textureIndex);
							else
								selected[mouseOver_groupIndex].Remove(mouseOver_textureIndex);
						}
					}
					else
					{
						if(mouseOver_textureIndex > -1)
							selected.Add(mouseOver_groupIndex, new List<int>() { mouseOver_textureIndex });
						else
							selected.Add(mouseOver_groupIndex, new List<int>());
					}

					GUIUtility.keyboardControl = 0;
					GUI.FocusControl("");
				}
				Repaint();
				break;

			case EventType.ContextClick:
				GenericMenu menu = new GenericMenu();
				menu.AddItem (new GUIContent("Open as Floating Window", ""), false, ContextOpenFloatingWindow);
				menu.AddItem (new GUIContent("Open as Dockable Window", ""), false, ContextOpenDockableWindow);
				menu.ShowAsContext ();
				e.Use();
				break;
		}
	}
        private static void ListUIHelper(string sectionTitle, IReadOnlyList <string> names, IReadOnlyList <string> descriptions, ref Vector2 scrollPosition, float maxHeightMultiplier = 1f)
        {
            int n = names.Count();

            Debug.Assert(descriptions.Count == n);
            if (descriptions.Count < n)
            {
                return;
            }

            GUILayout.Space(k_Space);
            GUILayout.Label(sectionTitle, EditorStyles.boldLabel);
            float height = Mathf.Min(n * 20f + 2f, 150f * maxHeightMultiplier);

            if (n == 0)
            {
                return;
            }

            scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUI.skin.box, GUILayout.MinHeight(height));
            Event e          = Event.current;
            float lineHeight = 16.0f;

            StringBuilder fullText = new StringBuilder();

            fullText.Append(sectionTitle);
            fullText.AppendLine();
            for (int i = 0; i < n; ++i)
            {
                string name        = names[i];
                string description = descriptions[i];
                fullText.Append($"{name} {description}");
                fullText.AppendLine();
            }

            for (int i = 0; i < n; ++i)
            {
                Rect r = EditorGUILayout.GetControlRect(false, lineHeight);

                string name        = names[i];
                string description = descriptions[i];

                // Context menu, "Copy"
                if (e.type == EventType.ContextClick && r.Contains(e.mousePosition))
                {
                    e.Use();
                    var menu = new GenericMenu();
                    // need to copy current value to be used in delegate
                    // (C# closures close over variables, not their values)
                    menu.AddItem(new GUIContent($"Copy current line"), false, delegate {
                        EditorGUIUtility.systemCopyBuffer = $"{name} {description}";
                    });
                    menu.AddItem(new GUIContent($"Copy section"), false, delegate {
                        EditorGUIUtility.systemCopyBuffer = fullText.ToString();
                    });
                    menu.ShowAsContext();
                }

                // Color even line for readability
                if (e.type == EventType.Repaint)
                {
                    GUIStyle st = "CN EntryBackEven";
                    if ((i & 1) == 0)
                    {
                        st.Draw(r, false, false, false, false);
                    }
                }

                // layer name on the right side
                Rect locRect = r;
                locRect.xMax = locRect.xMin;
                GUIContent gc = new GUIContent(name.ToString(CultureInfo.InvariantCulture));

                // calculate size so we can left-align it
                Vector2 size = EditorStyles.miniBoldLabel.CalcSize(gc);
                locRect.xMax += size.x;
                GUI.Label(locRect, gc, EditorStyles.miniBoldLabel);
                locRect.xMax += 2;

                // message
                Rect msgRect = r;
                msgRect.xMin = locRect.xMax;
                GUI.Label(msgRect, new GUIContent(description.ToString(CultureInfo.InvariantCulture)), EditorStyles.miniLabel);
            }
            GUILayout.EndScrollView();
        }
Ejemplo n.º 40
0
		public override void OnFlowWindowGUI(FD.FlowWindow window) {

			if (Social.settings == null) return;

			var socialFlag = (window.flags & Social.settings.uniqueTag) == Social.settings.uniqueTag;
			if (socialFlag == true) {

				var settings = Social.settings;
				if (settings == null) return;
				
				var data = settings.data.Get(window);
				var isActiveSelected = settings.IsPlatformActive(data.settings);

				var oldColor = GUI.color;
				GUI.color = isActiveSelected ? Color.white : Color.grey;
				var result = GUILayoutExt.LargeButton(data.settings ? data.settings.GetPlatformName() : "None", 60f, 150f);
				GUI.color = oldColor;
				var rect = GUILayoutUtility.GetLastRect();
				rect.y += rect.height;

				if (result == true) {

					var menu = new GenericMenu();
					menu.AddItem(new GUIContent("None"), data.settings == null, () => {

						data.settings = null;

					});

					foreach (var platform in settings.activePlatforms) {

						if (platform.active == true) {

							var item = platform.settings;
							menu.AddItem(new GUIContent(platform.GetPlatformName()), data.settings == platform.settings, () => {

								data.settings = item;

							});
							
						} else {

							menu.AddDisabledItem(new GUIContent(platform.GetPlatformName()));

						}
						
					}

					menu.DropDown(rect);

				}

			}

		}
Ejemplo n.º 41
0
        public override void OnInspectorGUI()
        {
            ME.ECSEditor.GUILayoutExt.CollectEditors <IGraphGUIEditor <Graph>, GraphCustomEditorAttribute>(ref this.graphEditors, System.Reflection.Assembly.GetExecutingAssembly());

            var target = (Pathfinding)this.target;

            if (this.styleDefaults == null)
            {
                this.styleDefaults = new UnityEditorInternal.ReorderableList.Defaults();
            }

            {
                GUILayout.Label(string.Empty, this.styleDefaults.headerBackground, GUILayout.ExpandWidth(true));
                var rect = GUILayoutUtility.GetLastRect();
                rect.x += 4f;
                GUI.Label(rect, "Graphs");
            }

            GUILayout.BeginVertical(this.styleDefaults.boxBackground);
            {
                for (int i = 0; i < target.graphs.Count; ++i)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Width(60f);
                    GUILayout.BeginVertical();

                    var graph = target.graphs[i];
                    graph.index = i;

                    if (this.graphEditors.TryGetValue(graph.GetType(), out var editor) == true)
                    {
                        editor.target = graph;

                        var state = ((GraphEditor)editor).foldout;
                        ME.ECSEditor.GUILayoutExt.FoldOut(ref state, graph.graphName, () => {
                            EditorGUI.BeginChangeCheck();
                            editor.OnDrawGUI();
                            if (EditorGUI.EndChangeCheck() == true)
                            {
                                EditorUtility.SetDirty(graph);
                                EditorUtility.SetDirty(this.target);
                                SceneView.RepaintAll();
                            }
                        }, onHeader: (rect) => {
                            var menu = new GenericMenu();
                            menu.AddItem(new GUIContent("Remove"), false, () => {
                                //Undo.RecordObject(target, "Remove Graph");
                                target.graphs.Remove(graph);
                                GameObject.DestroyImmediate(graph.gameObject);
                                SceneView.RepaintAll();
                                EditorUtility.SetDirty(this.target);
                            });
                            menu.DropDown(rect);
                        });
                        ((GraphEditor)editor).foldout = state;
                    }
                    else
                    {
                        GUILayout.Label("No editor found for " + graph.GetType());
                    }
                    GUILayout.EndVertical();
                    GUILayout.EndHorizontal();
                }
            }
            GUILayout.EndVertical();

            GUILayout.BeginHorizontal();
            {
                GUILayout.FlexibleSpace();
                GUILayout.BeginHorizontal(this.styleDefaults.footerBackground);
                var rect = GUILayoutUtility.GetRect(50f, 16f);
                if (GUI.Button(rect, this.styleDefaults.iconToolbarPlusMore, this.styleDefaults.preButton) == true)
                {
                    var menu = new GenericMenu();
                    foreach (var graph in this.graphEditors)
                    {
                        var g = graph;
                        if (g.Key.IsAbstract == true)
                        {
                            continue;
                        }
                        menu.AddItem(new GUIContent(graph.Key.Name), false, () => {
                            var go = new GameObject("Graph", g.Key);
                            go.transform.SetParent(target.transform);
                            var comp = (Graph)go.GetComponent(g.Key);
                            comp.pathfindingLogLevel = target.logLevel;
                            target.graphs.Add(comp);
                            SceneView.RepaintAll();
                            EditorUtility.SetDirty(this.target);
                        });
                    }
                    menu.DropDown(rect);
                }
                GUILayout.EndHorizontal();
            }
            GUILayout.EndHorizontal();

            ME.ECSEditor.GUILayoutExt.Separator();

            { // Editor
                var state = this.editorFoldout;
                ME.ECSEditor.GUILayoutExt.FoldOut(ref state, "Editor", () => {
                    EditorGUI.BeginChangeCheck();
                    target.logLevel = (LogLevel)EditorGUILayout.EnumFlagsField("Log Level", target.logLevel);
                    if (EditorGUI.EndChangeCheck() == true)
                    {
                        EditorUtility.SetDirty(this.target);
                        SceneView.RepaintAll();
                    }
                });
                this.editorFoldout = state;
            }

            ME.ECSEditor.GUILayoutExt.Separator();

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Build All", GUILayout.Width(200f), GUILayout.Height(24f)) == true)
            {
                target.BuildAll();
                SceneView.RepaintAll();
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
        }
Ejemplo n.º 42
0
    public override void OnInspectorGUI()
    {
        DrawToolbarGUI();

        bool dirty = DrawGeneralGUI();

        EditorGUILayout.BeginVertical(GUI.skin.box);
        showMarkers = Foldout(showMarkers, "2D Markers");
        if (showMarkers) DrawMarkersGUI();
        EditorGUILayout.EndVertical();

        if (api.target == OnlineMapsTarget.texture)
        {
            EditorGUILayout.BeginVertical(GUI.skin.box);
            showCreateTexture = Foldout(showCreateTexture, "Create texture");
            if (showCreateTexture) DrawCreateTextureGUI(ref dirty);
            EditorGUILayout.EndVertical();
        }

        EditorGUILayout.BeginVertical(GUI.skin.box);
        showAdvanced = Foldout(showAdvanced, "Advanced");
        if (showAdvanced) DrawAdvancedGUI(ref dirty);
        EditorGUILayout.EndVertical();

        EditorGUILayout.BeginVertical(GUI.skin.box);
        showTroubleshooting = Foldout(showTroubleshooting, "Troubleshooting");
        if (showTroubleshooting) DrawTroubleshootingGUI(ref dirty);
        EditorGUILayout.EndVertical();

        OnlineMapsControlBase[] controls = api.GetComponents<OnlineMapsControlBase>();
        if (controls == null || controls.Length == 0)
        {
            EditorGUILayout.BeginVertical(GUI.skin.box);

            EditorGUILayout.HelpBox("Problem detected:\nCan not find OnlineMaps Control component.", MessageType.Error);
            if (GUILayout.Button("Add Control"))
            {
                GenericMenu menu = new GenericMenu();

                Type[] types = api.GetType().Assembly.GetTypes();
                foreach (Type t in types)
                {
                    if (t.IsSubclassOf(typeof(OnlineMapsControlBase)))
                    {
                        if (t == typeof(OnlineMapsControlBase2D) || t == typeof(OnlineMapsControlBase3D)) continue;

                        string fullName = t.FullName.Substring(10);

                        int controlIndex = fullName.IndexOf("Control");
                        fullName = fullName.Insert(controlIndex, " ");

                        int textureIndex = fullName.IndexOf("Texture");
                        if (textureIndex > 0) fullName = fullName.Insert(textureIndex, " ");

                        menu.AddItem(new GUIContent(fullName), false, data =>
                        {
                            Type ct = data as Type;
                            api.gameObject.AddComponent(ct);
                            api.target = (ct == typeof (OnlineMapsTileSetControl))
                                ? OnlineMapsTarget.tileset
                                : OnlineMapsTarget.texture;
                            Repaint();
                        }, t);
                    }
                }

                menu.ShowAsContext();
            }

            EditorGUILayout.EndVertical();
        }

        if (dirty)
        {
            EditorUtility.SetDirty(api);
            Repaint();
        }
    }
Ejemplo n.º 43
0
        private void ActionSideMenu(int i)
        {
            ActionList _target = (ActionList)target;

            actionToAffect = _target.actions[i];
            GenericMenu menu = new GenericMenu();

            if (_target.actions[i].isEnabled)
            {
                menu.AddItem(new GUIContent("Disable"), false, Callback, "Disable");
            }
            else
            {
                menu.AddItem(new GUIContent("Enable"), false, Callback, "Enable");
            }
            menu.AddSeparator("");
            if (!Application.isPlaying)
            {
                if (_target.actions.Count > 1)
                {
                    menu.AddItem(new GUIContent("Cut"), false, Callback, "Cut");
                }
                menu.AddItem(new GUIContent("Copy"), false, Callback, "Copy");
            }
            if (AdvGame.copiedActions.Count > 0)
            {
                menu.AddItem(new GUIContent("Paste after"), false, Callback, "Paste after");
            }
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("Insert after"), false, Callback, "Insert after");
            if (_target.actions.Count > 1)
            {
                menu.AddItem(new GUIContent("Delete"), false, Callback, "Delete");
            }
            if (i > 0 || i < _target.actions.Count - 1)
            {
                menu.AddSeparator("");
            }
            if (i > 0)
            {
                menu.AddItem(new GUIContent("Re-arrange/Move to top"), false, Callback, "Move to top");
                menu.AddItem(new GUIContent("Re-arrange/Move up"), false, Callback, "Move up");
            }
            if (i < _target.actions.Count - 1)
            {
                menu.AddItem(new GUIContent("Re-arrange/Move down"), false, Callback, "Move down");
                menu.AddItem(new GUIContent("Re-arrange/Move to bottom"), false, Callback, "Move to bottom");
            }

            menu.AddSeparator("");
            menu.AddItem(new GUIContent("Toggle breakpoint"), false, Callback, "Toggle breakpoint");

            menu.ShowAsContext();
        }
        void OnPropertyContextMenu(GenericMenu menu, PropertyModification[] modifications)
        {
            bool hasKey       = m_Responder.KeyExists(modifications);
            bool hasCandidate = m_Responder.CandidateExists(modifications);
            bool hasCurve     = (hasKey || m_Responder.CurveExists(modifications));

            bool hasAnyCandidate = m_Responder.HasAnyCandidates();
            bool hasAnyCurve     = m_Responder.HasAnyCurves();

            menu.AddItem(((hasKey && hasCandidate) ? updateKeyContent : addKeyContent), false, () => {
                m_Responder.AddKey(modifications);
            });

            if (hasKey)
            {
                menu.AddItem(removeKeyContent, false, () => {
                    m_Responder.RemoveKey(modifications);
                });
            }
            else
            {
                menu.AddDisabledItem(removeKeyContent);
            }

            if (hasCurve)
            {
                menu.AddItem(removeCurveContent, false, () => {
                    m_Responder.RemoveCurve(modifications);
                });
            }
            else
            {
                menu.AddDisabledItem(removeCurveContent);
            }

            menu.AddSeparator(string.Empty);
            if (hasAnyCandidate)
            {
                menu.AddItem(addCandidatesContent, false, () => {
                    m_Responder.AddCandidateKeys();
                });
            }
            else
            {
                menu.AddDisabledItem(addCandidatesContent);
            }

            if (hasAnyCurve)
            {
                menu.AddItem(addAnimatedContent, false, () => {
                    m_Responder.AddAnimatedKeys();
                });
            }
            else
            {
                menu.AddDisabledItem(addAnimatedContent);
            }

            menu.AddSeparator(string.Empty);
            if (hasCurve)
            {
                menu.AddItem(goToPreviousKeyContent, false, () => {
                    m_Responder.GoToPreviousKeyframe(modifications);
                });
                menu.AddItem(goToNextKeyContent, false, () => {
                    m_Responder.GoToNextKeyframe(modifications);
                });
            }
            else
            {
                menu.AddDisabledItem(goToPreviousKeyContent);
                menu.AddDisabledItem(goToNextKeyContent);
            }
        }
Ejemplo n.º 45
0
	void Selector(SerializedProperty property) {
		SkeletonData data = skeletonDataAsset.GetSkeletonData(true);

		if (data == null)
			return;

		SpineAttachment attrib = (SpineAttachment)attribute;

		List<Skin> validSkins = new List<Skin>();

		if (skeletonRenderer != null && attrib.currentSkinOnly) {
			if (skeletonRenderer.skeleton.Skin != null) {
				validSkins.Add(skeletonRenderer.skeleton.Skin);
			} else {
				validSkins.Add(data.Skins.Items[0]);
			}
		} else {
			foreach (Skin skin in data.Skins) {
				if (skin != null)
					validSkins.Add(skin);
			}
		}

		GenericMenu menu = new GenericMenu();
		List<string> attachmentNames = new List<string>();
		List<string> placeholderNames = new List<string>();

		string prefix = "";

		if (skeletonRenderer != null && attrib.currentSkinOnly)
			menu.AddDisabledItem(new GUIContent(skeletonRenderer.gameObject.name + " (SkeletonRenderer)"));
		else
			menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
		menu.AddSeparator("");

		menu.AddItem(new GUIContent("Null"), property.stringValue == "", HandleSelect, new SpineDrawerValuePair("", property));
		menu.AddSeparator("");

		Skin defaultSkin = data.Skins.Items[0];

		SerializedProperty slotProperty = property.serializedObject.FindProperty(attrib.slotField);
		string slotMatch = "";
		if (slotProperty != null) {
			if (slotProperty.propertyType == SerializedPropertyType.String) {
				slotMatch = slotProperty.stringValue.ToLower();
			}
		}

		foreach (Skin skin in validSkins) {
			string skinPrefix = skin.Name + "/";

			if (validSkins.Count > 1)
				prefix = skinPrefix;

			for (int i = 0; i < data.Slots.Count; i++) {
				if (slotMatch.Length > 0 && data.Slots.Items[i].Name.ToLower().Contains(slotMatch) == false)
					continue;

				attachmentNames.Clear();
				placeholderNames.Clear();

				skin.FindNamesForSlot(i, attachmentNames);
				if (skin != defaultSkin) {
					defaultSkin.FindNamesForSlot(i, attachmentNames);
					skin.FindNamesForSlot(i, placeholderNames);
				}
					

				for (int a = 0; a < attachmentNames.Count; a++) {
					
					string attachmentPath = attachmentNames[a];
					string menuPath = prefix + data.Slots.Items[i].Name + "/" + attachmentPath;
					string name = attachmentNames[a];

					if (attrib.returnAttachmentPath)
						name = skin.Name + "/" + data.Slots.Items[i].Name + "/" + attachmentPath;

					if (attrib.placeholdersOnly && placeholderNames.Contains(attachmentPath) == false) {
						menu.AddDisabledItem(new GUIContent(menuPath));
					} else {
						menu.AddItem(new GUIContent(menuPath), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
					}
					
					
				}
			}
		}


		menu.ShowAsContext();
	}
Ejemplo n.º 46
0
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            int isGlobal = m_IsGlobal.boolValue ? 0 : 1;

            isGlobal             = EditorGUILayout.Popup(EditorGUIUtility.TrTextContent("Mode", "A global volume is applied to the whole scene."), isGlobal, m_Modes);
            m_IsGlobal.boolValue = isGlobal == 0;

            if (isGlobal != 0) // Blend radius is not needed for global volumes
            {
                if (!actualTarget.TryGetComponent <Collider>(out _))
                {
                    EditorGUILayout.HelpBox("Add a Collider to this GameObject to set boundaries for the local Volume.", MessageType.Info);

                    if (GUILayout.Button(EditorGUIUtility.TrTextContent("Add Collider"), EditorStyles.miniButton))
                    {
                        var menu = new GenericMenu();
                        menu.AddItem(EditorGUIUtility.TrTextContent("Box"), false, () => Undo.AddComponent <BoxCollider>(actualTarget.gameObject));
                        menu.AddItem(EditorGUIUtility.TrTextContent("Sphere"), false, () => Undo.AddComponent <SphereCollider>(actualTarget.gameObject));
                        menu.AddItem(EditorGUIUtility.TrTextContent("Capsule"), false, () => Undo.AddComponent <CapsuleCollider>(actualTarget.gameObject));
                        menu.AddItem(EditorGUIUtility.TrTextContent("Mesh"), false, () => Undo.AddComponent <MeshCollider>(actualTarget.gameObject));
                        menu.ShowAsContext();
                    }
                }

                EditorGUILayout.PropertyField(m_BlendRadius);
                m_BlendRadius.floatValue = Mathf.Max(m_BlendRadius.floatValue, 0f);
            }

            EditorGUILayout.PropertyField(m_Weight);
            EditorGUILayout.PropertyField(m_Priority);

            bool assetHasChanged = false;
            bool showCopy        = m_Profile.objectReferenceValue != null;
            bool multiEdit       = m_Profile.hasMultipleDifferentValues;

            // The layout system breaks alignment when mixing inspector fields with custom layout'd
            // fields, do the layout manually instead
            int   buttonWidth    = showCopy ? 45 : 60;
            float indentOffset   = EditorGUI.indentLevel * 15f;
            var   lineRect       = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
            var   labelRect      = new Rect(lineRect.x, lineRect.y, EditorGUIUtility.labelWidth - indentOffset, lineRect.height);
            var   fieldRect      = new Rect(labelRect.xMax, lineRect.y, lineRect.width - labelRect.width - buttonWidth * (showCopy ? 2 : 1), lineRect.height);
            var   buttonNewRect  = new Rect(fieldRect.xMax, lineRect.y, buttonWidth, lineRect.height);
            var   buttonCopyRect = new Rect(buttonNewRect.xMax, lineRect.y, buttonWidth, lineRect.height);

            GUIContent guiContent;

            if (actualTarget.HasInstantiatedProfile())
            {
                guiContent = EditorGUIUtility.TrTextContent("Profile (Instance)", "A copy of a profile asset.");
            }
            else
            {
                guiContent = EditorGUIUtility.TrTextContent("Profile", "A reference to a profile asset.");
            }
            EditorGUI.PrefixLabel(labelRect, guiContent);

            using (var scope = new EditorGUI.ChangeCheckScope())
            {
                EditorGUI.BeginProperty(fieldRect, GUIContent.none, m_Profile);

                VolumeProfile profile;

                if (actualTarget.HasInstantiatedProfile())
                {
                    profile = (VolumeProfile)EditorGUI.ObjectField(fieldRect, actualTarget.profile, typeof(VolumeProfile), false);
                }
                else
                {
                    profile = (VolumeProfile)EditorGUI.ObjectField(fieldRect, m_Profile.objectReferenceValue, typeof(VolumeProfile), false);
                }

                if (scope.changed)
                {
                    assetHasChanged = true;
                    m_Profile.objectReferenceValue = profile;

                    if (actualTarget.HasInstantiatedProfile()) // Clear the instantiated profile, from now on we're using shared again
                    {
                        actualTarget.profile = null;
                    }
                }

                EditorGUI.EndProperty();
            }

            using (new EditorGUI.DisabledScope(multiEdit))
            {
                if (GUI.Button(buttonNewRect, EditorGUIUtility.TrTextContent("New", "Create a new profile."), showCopy ? EditorStyles.miniButtonLeft : EditorStyles.miniButton))
                {
                    // By default, try to put assets in a folder next to the currently active
                    // scene file. If the user isn't a scene, put them in root instead.
                    var targetName = actualTarget.name;
                    var scene      = actualTarget.gameObject.scene;
                    var asset      = VolumeProfileFactory.CreateVolumeProfile(scene, targetName);
                    m_Profile.objectReferenceValue = asset;
                    actualTarget.profile           = null; // Make sure we're not using an instantiated profile anymore
                    assetHasChanged = true;
                }

                if (actualTarget.HasInstantiatedProfile())
                {
                    guiContent = EditorGUIUtility.TrTextContent("Save", "Save the instantiated profile");
                }
                else
                {
                    guiContent = EditorGUIUtility.TrTextContent("Clone", "Create a new profile and copy the content of the currently assigned profile.");
                }
                if (showCopy && GUI.Button(buttonCopyRect, guiContent, EditorStyles.miniButtonRight))
                {
                    // Duplicate the currently assigned profile and save it as a new profile
                    var origin = profileRef;
                    var path   = AssetDatabase.GetAssetPath(m_Profile.objectReferenceValue);
                    path = AssetDatabase.GenerateUniqueAssetPath(path);

                    var asset = Instantiate(origin);
                    asset.components.Clear();
                    AssetDatabase.CreateAsset(asset, path);

                    foreach (var item in origin.components)
                    {
                        var itemCopy = Instantiate(item);
                        itemCopy.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy;
                        itemCopy.name      = item.name;
                        asset.components.Add(itemCopy);
                        AssetDatabase.AddObjectToAsset(itemCopy, asset);
                    }

                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();

                    m_Profile.objectReferenceValue = asset;
                    actualTarget.profile           = null; // Make sure we're not using an instantiated profile anymore
                    assetHasChanged = true;
                }
            }

            EditorGUILayout.Space();

            if (m_Profile.objectReferenceValue == null && !actualTarget.HasInstantiatedProfile())
            {
                if (assetHasChanged)
                {
                    m_ComponentList.Clear(); // Asset wasn't null before, do some cleanup
                }
            }
            else
            {
                if (assetHasChanged || profileRef != m_ComponentList.asset)
                {
                    RefreshEffectListEditor(profileRef);
                }

                if (!multiEdit)
                {
                    m_ComponentList.OnGUI();
                    EditorGUILayout.Space();
                }
            }

            serializedObject.ApplyModifiedProperties();
        }
Ejemplo n.º 47
0
	void Selector(SerializedProperty property) {
		SpineSlot attrib = (SpineSlot)attribute;
		SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
		if (data == null)
			return;

		GenericMenu menu = new GenericMenu();

		menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
		menu.AddSeparator("");

		for (int i = 0; i < data.Slots.Count; i++) {
			string name = data.Slots.Items[i].Name;
			if (name.StartsWith(attrib.startsWith)) {
				if (attrib.containsBoundingBoxes) {

					int slotIndex = i;

					List<Attachment> attachments = new List<Attachment>();
					foreach (var skin in data.Skins) {
						skin.FindAttachmentsForSlot(slotIndex, attachments);
					}

					bool hasBoundingBox = false;
					foreach (var attachment in attachments) {
						if (attachment is BoundingBoxAttachment) {
							menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
							hasBoundingBox = true;
							break;
						}
					}

					if (!hasBoundingBox)
						menu.AddDisabledItem(new GUIContent(name));
					

				} else {
					menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
				}
				
			}
				
		}

		menu.ShowAsContext();
	}
Ejemplo n.º 48
0
        void UpdateMenuItems(GenericMenu menu)
        {
            SelectedHistoryGroupInfo info =
                mOperations.GetSelectedHistoryGroupInfo();

            HistoryMenuOperations operations =
                HistoryMenuUpdater.GetAvailableMenuOperations(info);

            if (operations == HistoryMenuOperations.None)
            {
                menu.AddDisabledItem(GetNoActionMenuItemContent(), false);
                return;
            }

            if (operations.HasFlag(HistoryMenuOperations.Open))
            {
                menu.AddItem(mOpenRevisionMenuItemContent, false, OpenRevisionMenu_Click);
            }
            else
            {
                menu.AddDisabledItem(mOpenRevisionMenuItemContent, false);
            }

            if (operations.HasFlag(HistoryMenuOperations.OpenWith))
            {
                menu.AddItem(mOpenRevisionWithMenuItemContent, false, OpenRevisionWithMenu_Click);
            }
            else
            {
                menu.AddDisabledItem(mOpenRevisionWithMenuItemContent, false);
            }

            if (operations.HasFlag(HistoryMenuOperations.SaveAs))
            {
                menu.AddItem(mSaveRevisionAsMenuItemContent, false, SaveRevisionasMenu_Click);
            }
            else
            {
                menu.AddDisabledItem(mSaveRevisionAsMenuItemContent, false);
            }

            menu.AddSeparator(string.Empty);

            if (operations.HasFlag(HistoryMenuOperations.DiffWithPrevious))
            {
                menu.AddItem(mDiffWithPreviousMenuItemContent, false, DiffWithPreviousMenuItem_Click);
            }

            if (operations.HasFlag(HistoryMenuOperations.DiffSelected))
            {
                menu.AddItem(mDiffSelectedRevisionsMenuItemContent, false, DiffSelectedRevisionsMenu_Click);
            }

            mDiffChangesetMenuItemContent.text =
                PlasticLocalization.GetString(PlasticLocalization.Name.HistoryMenuItemDiffChangeset) +
                string.Format(" {0}", GetSelectedChangesetName(mMenuOperations));

            if (operations.HasFlag(HistoryMenuOperations.DiffChangeset))
            {
                menu.AddItem(mDiffChangesetMenuItemContent, false, DiffChangesetMenu_Click);
            }
            else
            {
                menu.AddDisabledItem(mDiffChangesetMenuItemContent, false);
            }

            menu.AddSeparator(string.Empty);

            if (operations.HasFlag(HistoryMenuOperations.RevertTo))
            {
                menu.AddItem(mRevertToThisRevisionMenuItemContent, false, RevertToThisRevisionMenu_Click);
            }
            else
            {
                menu.AddDisabledItem(mRevertToThisRevisionMenuItemContent, false);
            }
        }
Ejemplo n.º 49
0
 void OnIdleContextClick( Event e )
 {
     if( currentNode == null )
     {
         GenericMenu menu = new GenericMenu();
         menu.AddItem( new GUIContent("New Menu"), false, Callback, "newScreen" );
         menu.ShowAsContext();
         e.Use();
     }
 }
 public void AddItem(GUIContent content, GenericMenu.MenuFunction handler)
 {
     _innerMenu.AddItem(content, false, handler);
 }
	void SpawnHierarchyContextMenu () {
		GenericMenu menu = new GenericMenu();

		menu.AddItem(new GUIContent("Follow"), false, SpawnFollowHierarchy);
		menu.AddItem(new GUIContent("Follow (Root Only)"), false, SpawnFollowHierarchyRootOnly);
		menu.AddSeparator("");
		menu.AddItem(new GUIContent("Override"), false, SpawnOverrideHierarchy);
		menu.AddItem(new GUIContent("Override (Root Only)"), false, SpawnOverrideHierarchyRootOnly);

		menu.ShowAsContext();
	}
Ejemplo n.º 52
0
 void AddNewPropertyBinderItem <T>(GenericMenu menu) where T : new()
 => menu.AddItem(PropertyBinderTypeLabel <T> .Content,
                 false, OnAddNewPropertyBinder <T>);
Ejemplo n.º 53
0
	public void OnGUI ()
	{
		if (EditorApplication.isCompiling || EditorApplication.isUpdating)
		{
			EditorGUILayout.LabelField("Please wait...", EditorStyles.centeredGreyMiniLabel);

			_cachedComponents = null;
			_selectedDisplay = null;
			_componentDisplays = null;
			_initialized = false;
			return;
		}

		if (!_initialized)
		{
			Initialize();
		}

		Transform transform = Selection.activeTransform;

		if (Selection.GetFiltered(typeof(Transform), SelectionMode.Unfiltered).Length > 0)
		{
			transform = (Transform)Selection.GetFiltered(typeof(Transform), SelectionMode.Unfiltered)[0];
		}

		if (transform == null)
		{
			EditorGUILayout.LabelField("Select a GameObject.", EditorStyles.centeredGreyMiniLabel);
			_cachedComponents = null;
			_selectedDisplay = null;
			_componentDisplays = null;
		}
		else
		{
			bool dirty = false;

			Component[] components = transform.GetComponents<Component>();

			if (_cachedComponents == null || _cachedComponents.Count != components.Length)
			{
				dirty = true;
			}
			else
			{
				for (int i = 0; i < components.Length; i++)
				{
					if (components[i] != _cachedComponents[i])
					{
						dirty = true;
						break;
					}
				}
			}

			if (dirty)
			{
				Dictionary<Component, ComponentDisplay> displays = new Dictionary<Component, ComponentDisplay>();
				_cachedComponents = new List<Component>(components);

				if (_componentDisplays == null)
				{
					_componentDisplays = new Dictionary<Component, ComponentDisplay>();
				}

				for (int i = 0; i < _cachedComponents.Count; i++)
				{
					Component component = _cachedComponents[i];

					if (component == null)
					{
						continue;
					}

					ComponentDisplay display = null;

					if (!_componentDisplays.TryGetValue(component, out display))
					{
						display = new ComponentDisplay();
						display.component = component;
					}

					displays[component] = display;
				}

				_componentDisplays = displays;
			}
		}

		if (_componentDisplays == null)
		{
			return;
		}

		_scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition);

		Editor editor = Editor.CreateEditor(transform.gameObject);
		editor.DrawHeader();

		if (transform != null)
		{
			for (int i = 0; i < _cachedComponents.Count; i++)
			{
				Component component = _cachedComponents[i];

				_componentDisplays[component].Draw(_componentDisplays[component] == _selectedDisplay);
			}

			ComponentDisplay hovered_display = null;

			for (int i = 0; i < _cachedComponents.Count; i++)
			{
				Component component = _cachedComponents[i];

				if (_componentDisplays[component].GetRect().Contains(Event.current.mousePosition))
				{
					hovered_display = _componentDisplays[component];
					break;
				}
			}

			if (hovered_display != null)
			{
				if (Event.current.type == EventType.ContextClick)
				{
					GenericMenu menu = new GenericMenu();
					menu.AddItem(new GUIContent("Move Up"), false, MoveUp, hovered_display.component);
					menu.AddItem(new GUIContent("Move Down"), false, MoveDown, hovered_display.component);

					menu.AddItem(new GUIContent("Move to Top"), false, MoveToTop, hovered_display.component);
					menu.AddItem(new GUIContent("Move to Bottom"), false, MoveToBottom, hovered_display.component);
					menu.ShowAsContext();
					Event.current.Use();
				}

				if (_selectedDisplay == null && Event.current.type == EventType.MouseDown && Event.current.button == 0)
				{
					_dragged = false;
					_selectedDisplay = hovered_display;
					Event.current.Use();
				}
			}

			if (_selectedDisplay != null) // Something was selected.
			{
				// If we're hovering over an option that's not the one we started on, treat this as a drag.
				if (hovered_display != null && _selectedDisplay != hovered_display)
				{
					_dragged = true;
				}

				// Draw where the component will be dropped.

				if (hovered_display != null)
				{
					Rect rect = new Rect(hovered_display.GetRect());
					rect.height = 1;

					GUI.Box(rect, "", destination);
				}
				else if (Event.current.mousePosition.y > _componentDisplays[_cachedComponents[_cachedComponents.Count - 1]].GetRect().y)
				{
					Rect rect = new Rect(_componentDisplays[_cachedComponents[_cachedComponents.Count - 1]].GetRect());
					rect.y += rect.height;
					rect.height = 1;

					GUI.Box(rect, "", destination);
				}
				else
				{
					Rect rect = new Rect(_componentDisplays[_cachedComponents[0]].GetRect());
					rect.height = 1;

					GUI.Box(rect, "", destination);
				}
			}

			if (Event.current.type == EventType.MouseUp && Event.current.button == 0)
			{
				if (_selectedDisplay != null && _selectedDisplay == hovered_display)
				{
					// If we didn't attempt to drag the component, and we're not over content, fold it out.
					if (!_dragged && !_selectedDisplay.GetContentRect().Contains(Event.current.mousePosition))
					{
						_selectedDisplay.Toggle();
					}

					_selectedDisplay = null;
					Event.current.Use();
				}
				else if (_selectedDisplay != null)
				{
					if (hovered_display != null)
					{
						int source_index = _cachedComponents.IndexOf(_selectedDisplay.component);
						int destination_index = _cachedComponents.IndexOf(hovered_display.component);

						int offset = destination_index - source_index;

						if (destination_index > source_index)
						{
							offset -= 1;
						}

						while (offset > 0)
						{
							UnityEditorInternal.ComponentUtility.MoveComponentDown(_selectedDisplay.component);
							offset --;
						}
						while (offset < 0)
						{
							UnityEditorInternal.ComponentUtility.MoveComponentUp(_selectedDisplay.component);
							offset ++;
						}
					}
					else if (Event.current.mousePosition.y > _componentDisplays[_cachedComponents[_cachedComponents.Count - 1]].GetRect().y)
					{
						MoveToBottom(_selectedDisplay.component);
					}
					else
					{
						MoveToTop(_selectedDisplay.component);
					}

					_selectedDisplay = null;
				}

				Event.current.Use();
			}
		}

		EditorGUILayout.EndScrollView();
	}
    private void ViewGUI()
    {
        #region 右键菜单
        if (Event.current.button == 1)
        {
            if (Event.current.type == EventType.MouseDown)
            {
                GenericMenu gm       = new GenericMenu();
                Vector2     mousePos = Event.current.mousePosition;
                gm.AddItem(new GUIContent("Add Target"), false, delegate()
                {
                    AddTarget(mousePos);
                });
                gm.AddItem(new GUIContent("Add Frame"), false, delegate()
                {
                    AddFrame();
                });
                gm.ShowAsContext();
            }
        }
        #endregion

        #region 移动视野
        if (Event.current.button == 2)
        {
            if (Event.current.type == EventType.MouseDown)
            {
                _mouseDownPos = Event.current.mousePosition;
            }
            else if (Event.current.type == EventType.MouseDrag)
            {
                Vector2 direction = (Event.current.mousePosition - _mouseDownPos);
                for (int i = 0; i < _LA.Targets.Count; i++)
                {
                    _LA.Targets[i].Anchor += direction;
                }
                _mouseDownPos = Event.current.mousePosition;
                Repaint();
            }
            Event.current.Use();
        }
        #endregion

        for (int i = 0; i < _LA.Targets.Count; i++)
        {
            LinkageAnimationTarget lat = _LA.Targets[i];

            #region 窗体锚点
            SetGUIState(Color.white, Color.white, true);
            if (GUI.RepeatButton(new Rect(lat.Anchor.x - 25, lat.Anchor.y - 15, 50, 30), ""))
            {
                lat.Anchor       = Event.current.mousePosition;
                _showTargetIndex = i;
                Repaint();
            }
            #endregion

            string style = (_showTargetIndex == i ? "flow node 0 on" : "flow node 0");
            GUI.BeginGroup(new Rect(lat.Anchor.x - _width / 2, lat.Anchor.y, _width, lat.Height), new GUIStyle(style));

            #region 动画目标物体
            int h = 5;
            SetGUIState(lat.Target ? Color.white : Color.red, Color.white, true);
            lat.Target = EditorGUI.ObjectField(new Rect(5, h, _width - 56, 16), lat.Target, typeof(GameObject), true) as GameObject;
            SetGUIState(Color.white, Color.cyan, true);
            if (GUI.Button(new Rect(_width - 46, h, 18, 16), lat.ShowPropertys ? "-" : "+"))
            {
                lat.ShowPropertys = !lat.ShowPropertys;
            }
            if (GUI.Button(new Rect(_width - 23, h, 18, 16), "x"))
            {
                if (EditorUtility.DisplayDialog("提示", "是否删除物体 " + (lat.Target ? lat.Target.name: "None") + " 及其所有动画属性、动画帧!", "确定", "取消"))
                {
                    RemoveTarget(lat);
                    break;
                }
            }
            h = h + 16 + _space;
            #endregion

            #region 属性列表
            if (lat.ShowPropertys)
            {
                SetGUIState(Color.white, Color.white, lat.Target);
                EditorGUI.LabelField(new Rect(5, h, _width - 10, 16), new GUIContent("Property List:"), "BoldLabel");
                h = h + 16 + _space;

                for (int j = 0; j < lat.Propertys.Count; j++)
                {
                    LAProperty lap = lat.Propertys[j];

                    string property = lap.ComponentName + "." + lap.PropertyName + "[" + lap.PropertyType + "]";
                    if (GUI.Button(new Rect(5, h, 18, 16), "x"))
                    {
                        if (EditorUtility.DisplayDialog("提示", "是否删除 " + lat.Target.name + " 的属性 " + property + "!", "确定", "取消"))
                        {
                            RemoveProperty(lat, j);
                            break;
                        }
                    }
                    EditorGUI.LabelField(new Rect(23, h, _width - 28, 16), property);
                    h = h + 16 + _space;

                    if (_showFrameIndex != -1)
                    {
                        switch (lap.PropertyType)
                        {
                        case "Bool":
                            bool oldB = (bool)lat.Frames[_showFrameIndex].GetFrameValue(j);
                            bool newB = EditorGUI.Toggle(new Rect(23, h, _width - 28, 16), oldB);
                            h = h + 16 + _space;
                            if (oldB != newB)
                            {
                                lat.Frames[_showFrameIndex].SetFrameValue(j, newB);
                            }
                            break;

                        case "Color":
                            Color oldC = (Color)lat.Frames[_showFrameIndex].GetFrameValue(j);
                            Color newC = EditorGUI.ColorField(new Rect(23, h, _width - 28, 16), oldC);
                            h = h + 16 + _space;
                            if (oldC != newC)
                            {
                                lat.Frames[_showFrameIndex].SetFrameValue(j, newC);
                            }
                            break;

                        case "Float":
                            float oldF = (float)lat.Frames[_showFrameIndex].GetFrameValue(j);
                            float newF = EditorGUI.FloatField(new Rect(23, h, _width - 28, 16), oldF);
                            h = h + 16 + _space;
                            if (oldF != newF)
                            {
                                lat.Frames[_showFrameIndex].SetFrameValue(j, newF);
                            }
                            break;

                        case "Int":
                            int oldI = (int)lat.Frames[_showFrameIndex].GetFrameValue(j);
                            int newI = EditorGUI.IntField(new Rect(23, h, _width - 28, 16), oldI);
                            h = h + 16 + _space;
                            if (oldI != newI)
                            {
                                lat.Frames[_showFrameIndex].SetFrameValue(j, newI);
                            }
                            break;

                        case "Quaternion":
                            Vector3 oldQ = ((Quaternion)lat.Frames[_showFrameIndex].GetFrameValue(j)).eulerAngles;
                            Vector3 newQ = EditorGUI.Vector3Field(new Rect(23, h, _width - 28, 16), "", oldQ);
                            h = h + 16 + _space;
                            if (oldQ != newQ)
                            {
                                lat.Frames[_showFrameIndex].SetFrameValue(j, Quaternion.Euler(newQ));
                            }
                            break;

                        case "String":
                            string oldS = (string)lat.Frames[_showFrameIndex].GetFrameValue(j);
                            string newS = EditorGUI.TextField(new Rect(23, h, _width - 28, 16), oldS);
                            h = h + 16 + _space;
                            if (oldS != newS)
                            {
                                lat.Frames[_showFrameIndex].SetFrameValue(j, newS);
                            }
                            break;

                        case "Vector2":
                            Vector2 oldV2 = (Vector2)lat.Frames[_showFrameIndex].GetFrameValue(j);
                            Vector2 newV2 = EditorGUI.Vector2Field(new Rect(23, h, _width - 28, 16), "", oldV2);
                            h = h + 16 + _space;
                            if (oldV2 != newV2)
                            {
                                lat.Frames[_showFrameIndex].SetFrameValue(j, newV2);
                            }
                            break;

                        case "Vector3":
                            Vector3 oldV3 = (Vector3)lat.Frames[_showFrameIndex].GetFrameValue(j);
                            Vector3 newV3 = EditorGUI.Vector3Field(new Rect(23, h, _width - 28, 16), "", oldV3);
                            h = h + 16 + _space;
                            if (oldV3 != newV3)
                            {
                                lat.Frames[_showFrameIndex].SetFrameValue(j, newV3);
                            }
                            break;

                        case "Vector4":
                            Vector4 oldV4 = (Vector4)lat.Frames[_showFrameIndex].GetFrameValue(j);
                            Vector4 newV4 = EditorGUI.Vector4Field(new Rect(23, h, _width - 28, 16), "", oldV4);
                            h = h + 16 + _space;
                            if (oldV4 != newV4)
                            {
                                lat.Frames[_showFrameIndex].SetFrameValue(j, newV4);
                            }
                            break;

                        case "Sprite":
                            Sprite oldSp = (Sprite)lat.Frames[_showFrameIndex].GetFrameValue(j);
                            Sprite newSp = EditorGUI.ObjectField(new Rect(23, h, _width - 28, 16), oldSp, typeof(Sprite), true) as Sprite;
                            h = h + 16 + _space;
                            if (oldSp != newSp)
                            {
                                lat.Frames[_showFrameIndex].SetFrameValue(j, newSp);
                            }
                            break;
                        }
                    }
                }
            }
            #endregion

            #region 添加属性
            if (lat.ShowPropertys)
            {
                if (GUI.Button(new Rect(5, h, _width - 10, 16), "Add Property"))
                {
                    GenericMenu gm  = new GenericMenu();
                    Component[] cps = lat.Target.GetComponents <Component>();
                    for (int m = 0; m < cps.Length; m++)
                    {
                        Type           type = cps[m].GetType();
                        PropertyInfo[] pis  = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                        for (int n = 0; n < pis.Length; n++)
                        {
                            PropertyInfo pi           = pis[n];
                            string       propertyType = pi.PropertyType.Name;
                            propertyType = LinkageAnimationTool.ReplaceType(propertyType);
                            bool allow = LinkageAnimationTool.IsAllowType(propertyType);

                            if (allow)
                            {
                                if (pi.CanRead && pi.CanWrite)
                                {
                                    gm.AddItem(new GUIContent(type.Name + "/" + "[" + propertyType + "] " + pi.Name), false, delegate()
                                    {
                                        LAProperty lap = new LAProperty(type.Name, propertyType, pi.Name);
                                        AddProperty(lat, lap);
                                    });
                                }
                            }
                        }
                    }
                    gm.ShowAsContext();
                }
                h = h + 16 + _space;
            }
            lat.Height = h;
            #endregion

            GUI.EndGroup();
        }
    }
Ejemplo n.º 55
0
		public override void OnFlowCreateMenuGUI(string prefix, GenericMenu menu) {

			if (this.InstallationNeeded() == false) {

				if (Social.settings != null) {

					menu.AddSeparator(prefix);

					menu.AddItem(new GUIContent(prefix + "Social"), on: false, func: () => {

						this.flowEditor.CreateNewItem(() => {

							var window = FlowSystem.CreateWindow(FD.FlowWindow.Flags.IsSmall | FD.FlowWindow.Flags.CantCompiled | Social.settings.uniqueTag);
							window.smallStyleDefault = "flow node 1";
							window.smallStyleSelected = "flow node 1 on";
							window.title = "Social";
							
							window.rect.width = 150f;
							window.rect.height = 100f;

							return window;

						});

					});

				}

			}

		}
Ejemplo n.º 56
0
        public void DrawConnection(List <NodeGUI> nodes, Dictionary <string, List <AssetReference> > assetGroups)
        {
            var startNode = nodes.Find(node => node.Id == OutputNodeId);

            if (startNode == null)
            {
                return;
            }

            var endNode = nodes.Find(node => node.Id == InputNodeId);

            if (endNode == null)
            {
                return;
            }

            var startPoint = m_outputPoint.GetGlobalPosition(startNode);
            var startV3    = new Vector3(startPoint.x, startPoint.y, 0f);

            var endPoint = m_inputPoint.GetGlobalPosition(endNode);
            var endV3    = new Vector3(endPoint.x, endPoint.y, 0f);

            var centerPoint   = startPoint + ((endPoint - startPoint) / 2);
            var centerPointV3 = new Vector3(centerPoint.x, centerPoint.y, 0f);

            var pointDistanceX = Model.Settings.GUI.CONNECTION_CURVE_LENGTH;

            var startTan = new Vector3(startPoint.x + pointDistanceX, centerPoint.y, 0f);
            var endTan   = new Vector3(endPoint.x - pointDistanceX, centerPoint.y, 0f);

            var totalAssets = 0;
            var totalGroups = 0;

            if (assetGroups != null)
            {
                totalAssets = assetGroups.Select(v => v.Value.Count).Sum();
                totalGroups = assetGroups.Keys.Count;
            }

            Color lineColor;
            var   lineWidth = (totalAssets > 0) ? 3f : 2f;

            if (IsSelected)
            {
                lineColor = Model.Settings.GUI.COLOR_ENABLED;
            }
            else
            {
                lineColor = (totalAssets > 0) ? Model.Settings.GUI.COLOR_CONNECTED : Model.Settings.GUI.COLOR_NOT_CONNECTED;
            }

            ConnectionGUIUtility.HandleMaterial.SetPass(0);
            Handles.DrawBezier(startV3, endV3, startTan, endTan, lineColor, null, lineWidth);

            // draw connection label if connection's label is not normal.
            GUIStyle labelStyle = new GUIStyle("WhiteMiniLabel");

            labelStyle.alignment = TextAnchor.MiddleLeft;

            switch (Label)
            {
            case Model.Settings.DEFAULT_OUTPUTPOINT_LABEL: {
                // show nothing
                break;
            }

            case Model.Settings.BUNDLECONFIG_BUNDLE_OUTPUTPOINT_LABEL: {
                var labelWidth   = labelStyle.CalcSize(new GUIContent(Model.Settings.BUNDLECONFIG_BUNDLE_OUTPUTPOINT_LABEL));
                var labelPointV3 = new Vector3(centerPointV3.x - (labelWidth.x / 2), centerPointV3.y - 24f, 0f);
                Handles.Label(labelPointV3, Model.Settings.BUNDLECONFIG_BUNDLE_OUTPUTPOINT_LABEL, labelStyle);
                break;
            }

            default: {
                var labelWidth   = labelStyle.CalcSize(new GUIContent(Label));
                var labelPointV3 = new Vector3(centerPointV3.x - (labelWidth.x / 2), centerPointV3.y - 24f, 0f);
                Handles.Label(labelPointV3, Label, labelStyle);
                break;
            }
            }

            string connectionLabel;

            if (totalGroups > 1)
            {
                connectionLabel = string.Format("{0}:{1}", totalAssets, totalGroups);
            }
            else
            {
                connectionLabel = string.Format("{0}", totalAssets);
            }

            var style = new GUIStyle(connectionButtonStyle);

            var labelSize = style.CalcSize(new GUIContent(connectionLabel));

            m_buttonRect = new Rect(centerPointV3.x - labelSize.x / 2f, centerPointV3.y - labelSize.y / 2f, labelSize.x, 30f);

            if (
                Event.current.type == EventType.ContextClick ||
                (Event.current.type == EventType.MouseUp && Event.current.button == 1)
                )
            {
                var rightClickPos = Event.current.mousePosition;
                if (m_buttonRect.Contains(rightClickPos))
                {
                    var menu = new GenericMenu();
                    menu.AddItem(
                        new GUIContent("Delete"),
                        false,
                        () => {
                        Delete();
                    }
                        );
                    menu.ShowAsContext();
                    Event.current.Use();
                }
            }

            if (GUI.Button(m_buttonRect, connectionLabel, style))
            {
                Inspector.UpdateInspector(this, assetGroups);
                ConnectionGUIUtility.ConnectionEventHandler(new ConnectionEvent(ConnectionEvent.EventType.EVENT_CONNECTION_TAPPED, this));
            }
        }
Ejemplo n.º 57
0
    private void DrawToolbarGUI()
    {
        GUILayout.BeginHorizontal(EditorStyles.toolbar);

        if (OnlineMapsUpdater.hasNewVersion && updateAvailableContent != null)
        {
            Color defBackgroundColor = GUI.backgroundColor;
            GUI.backgroundColor = new Color(1, 0.5f, 0.5f);
            if (GUILayout.Button(updateAvailableContent, EditorStyles.toolbarButton))
            {
                OnlineMapsUpdater.OpenWindow();
            }
            GUI.backgroundColor = defBackgroundColor;
        }
        else GUILayout.Label("");

        if (GUILayout.Button("Help", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
        {
            GenericMenu menu = new GenericMenu();
            menu.AddItem(new GUIContent("Documentation"), false, OnViewDocs);
            menu.AddItem(new GUIContent("API Reference"), false, OnViewAPI);
            menu.AddItem(new GUIContent("Atlas of Examples"), false, OnViewAtlas);
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("Product Page"), false, OnProductPage);
            menu.AddItem(new GUIContent("Forum"), false, OnViewForum);
            menu.AddItem(new GUIContent("Check Updates"), false, OnCheckUpdates);
            menu.AddItem(new GUIContent("Support"), false, OnSendMail);
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("About"), false, OnAbout);
            menu.ShowAsContext();
        }

        GUILayout.EndHorizontal();
    }
Ejemplo n.º 58
0
        // private static GenericMenu BuildPopupList(UnityEngine.Object target, UnityEventBase dummyEvent, SerializedProperty listener)
        private static GenericMenu BuildPopupList(string target, UnityEventBase dummyEvent, SerializedProperty listener)
        {
            // var funBpl = typeof(UnityEventDrawer).GetMethod("BuildPopupList", BindingFlags.NonPublic | BindingFlags.Static);
            // return (GenericMenu) funBpl.Invoke(null, new object[]{target, dummyEvent, listener});
            SerializedProperty propertyRelative = listener.FindPropertyRelative("_methodName");

            var m   = new GenericMenu();
            int num = string.IsNullOrEmpty(propertyRelative.stringValue) ? 1 : 0;

            if (_menuCallBack0 == null)
            {
                _menuCallBack0 = new GenericMenu.MenuFunction2(ClearEventFunction);
            }
            var fMgCache0 = _menuCallBack0;
            var local     = (ValueType) new UnityEventFunction(listener, null, null, PersistentListenerMode.EventDefined, null);
            var content   = new GUIContent("No Function");

            m.AddItem(content, num != 0, fMgCache0, local);
            if (string.IsNullOrEmpty(target))
            {
                return(m);
            }
            m.AddSeparator("");
            var array = dummyEvent.GetType().GetMethod("Invoke")?.GetParameters().Select(x => x.ParameterType).ToArray();

            GeneratePopUpForType(m, target, true, listener, array);
            // var vmProps = Util.ViewModelProvider.GetViewModelProperties(target);
            //var vmMeths = Util.ViewModelProvider.GetViewModelBindEventMethods(target);
            //foreach (var methodInfo in vmMeths)
            //{
            //    m.AddItem(new GUIContent(methodInfo.Name), num != 0, () => { });
            //}
            //GeneratePopUpForType(m, target,true,listener,array);
            // m.AddItem(new GUIContent("dsd"),true, ()=> {});
            return(m);
            //UnityEngine.Object target1 = target;
            //if (target1 is Component com)
            //    target1 = com.gameObject;
            //SerializedProperty propertyRelative = listener.FindPropertyRelative("_methodName");
            //GenericMenu menu = new GenericMenu();
            //GenericMenu genericMenu = menu;
            //GUIContent content = new GUIContent("No Function");
            //int num = string.IsNullOrEmpty(propertyRelative.stringValue) ? 1 : 0;
            //// ISSUE: reference to a compiler-generated field
            //if (_menuCallBack0 == null)
            //{
            //    // ISSUE: reference to a compiler-generated field
            //    _menuCallBack0 = new GenericMenu.MenuFunction2(ClearEventFunction);
            //}
            //// ISSUE: reference to a compiler-generated field
            //GenericMenu.MenuFunction2 fMgCache0 = _menuCallBack0;
            //// ISSUE: variable of a boxed type
            //var local = (ValueType)new UnityEventFunction(listener, (UnityEngine.Object)null, (MethodInfo)null, PersistentListenerMode.EventDefined);
            //genericMenu.AddItem(content, num != 0, fMgCache0, (object)local);
            //if (target1 == (UnityEngine.Object)null)
            //    return menu;
            //menu.AddSeparator("");
            //System.Type[] array = ((IEnumerable<System.Reflection.ParameterInfo>)dummyEvent.GetType().GetMethod("Invoke").GetParameters()).Select<System.Reflection.ParameterInfo, System.Type>((Func<System.Reflection.ParameterInfo, System.Type>)(x => x.ParameterType)).ToArray<System.Type>();
            //GeneratePopUpForType(menu, target1, false, listener, array);
            //if (target1 is GameObject)
            //{
            //    Component[] components = (target1 as GameObject).GetComponents<Component>();
            //    List<string> list = ((IEnumerable<Component>)components).Where<Component>((Func<Component, bool>)(c => (UnityEngine.Object)c != (UnityEngine.Object)null)).Select<Component, string>((Func<Component, string>)(c => c.GetType().Name)).GroupBy<string, string>((Func<string, string>)(x => x)).Where<IGrouping<string, string>>((Func<IGrouping<string, string>, bool>)(g => g.Count<string>() > 1)).Select<IGrouping<string, string>, string>((Func<IGrouping<string, string>, string>)(g => g.Key)).ToList<string>();
            //    foreach (Component component in components)
            //    {
            //        if (!((UnityEngine.Object)component == (UnityEngine.Object)null))
            //            GeneratePopUpForType(menu, (UnityEngine.Object)component, list.Contains(component.GetType().Name), listener, array);
            //    }
            //}
            //return menu;
        }
Ejemplo n.º 59
0
    private bool BakeButton(params GUILayoutOption[] options)
    {
        GUIContent content = new GUIContent (ObjectNames.NicifyVariableName (bakeMode.ToString ()));

        Rect dropdownRect = GUILayoutUtility.GetRect (content, (GUIStyle)"DropDownButton", options);
        Rect buttonRect = dropdownRect;
        buttonRect.xMin = buttonRect.xMax - 20;
        if (Event.current.type != EventType.MouseDown || !buttonRect.Contains (Event.current.mousePosition))
            return GUI.Button (dropdownRect, content, (GUIStyle)"DropDownButton");
        GenericMenu genericMenu = new GenericMenu ();
        string[] names = Enum.GetNames (typeof(BakeMode));
        int num1 = Array.IndexOf<string> (names, Enum.GetName (typeof(BakeMode), this.bakeMode));
        int num2 = 0;
        foreach (string text in Enumerable.Select<string, string> (names, x => ObjectNames.NicifyVariableName(x))) {
            genericMenu.AddItem (new GUIContent (text), num2 == num1, new GenericMenu.MenuFunction2 (this.BakeDropDownCallback), num2++);
        }
        genericMenu.DropDown (dropdownRect);
        Event.current.Use ();
        return false;
    }
Ejemplo n.º 60
0
        private GenericMenu GenerateMenu(List <AnimationWindowHierarchyNode> interactedNodes)
        {
            List <AnimationWindowCurve> curvesAffectedByNodes1 = this.GetCurvesAffectedByNodes(interactedNodes, false);
            List <AnimationWindowCurve> curvesAffectedByNodes2 = this.GetCurvesAffectedByNodes(interactedNodes, true);
            bool        flag1       = curvesAffectedByNodes1.Count == 1 && AnimationWindowUtility.ForceGrouping(curvesAffectedByNodes1[0].binding);
            GenericMenu genericMenu = new GenericMenu();

            genericMenu.AddItem(new GUIContent(curvesAffectedByNodes1.Count > 1 || flag1 ? "Remove Properties" : "Remove Property"), false, new GenericMenu.MenuFunction(this.RemoveCurvesFromSelectedNodes));
            bool flag2 = true;

            EditorCurveBinding[] curves = new EditorCurveBinding[curvesAffectedByNodes2.Count];
            for (int index = 0; index < curvesAffectedByNodes2.Count; ++index)
            {
                curves[index] = curvesAffectedByNodes2[index].binding;
            }
            RotationCurveInterpolation.Mode interpolationMode = this.GetRotationInterpolationMode(curves);
            if (interpolationMode == RotationCurveInterpolation.Mode.Undefined)
            {
                flag2 = false;
            }
            else
            {
                using (List <AnimationWindowHierarchyNode> .Enumerator enumerator = interactedNodes.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        if (!(enumerator.Current is AnimationWindowHierarchyPropertyGroupNode))
                        {
                            flag2 = false;
                        }
                    }
                }
            }
            if (flag2)
            {
                string str = !this.state.activeAnimationClip.legacy ? string.Empty : " (Not fully supported in Legacy)";
                genericMenu.AddItem(new GUIContent("Interpolation/Euler Angles" + str), interpolationMode == RotationCurveInterpolation.Mode.RawEuler, new GenericMenu.MenuFunction2(this.ChangeRotationInterpolation), (object)RotationCurveInterpolation.Mode.RawEuler);
                genericMenu.AddItem(new GUIContent("Interpolation/Euler Angles (Quaternion Approximation)"), interpolationMode == RotationCurveInterpolation.Mode.Baked, new GenericMenu.MenuFunction2(this.ChangeRotationInterpolation), (object)RotationCurveInterpolation.Mode.Baked);
                genericMenu.AddItem(new GUIContent("Interpolation/Quaternion"), interpolationMode == RotationCurveInterpolation.Mode.NonBaked, new GenericMenu.MenuFunction2(this.ChangeRotationInterpolation), (object)RotationCurveInterpolation.Mode.NonBaked);
            }
            if (AnimationMode.InAnimationMode())
            {
                genericMenu.AddSeparator(string.Empty);
                bool flag3 = true;
                bool flag4 = true;
                bool flag5 = true;
                using (List <AnimationWindowCurve> .Enumerator enumerator = curvesAffectedByNodes1.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        AnimationWindowCurve current = enumerator.Current;
                        if (!current.HasKeyframe(this.state.time))
                        {
                            flag3 = false;
                        }
                        else
                        {
                            flag4 = false;
                            if (!current.isPPtrCurve)
                            {
                                flag5 = false;
                            }
                        }
                    }
                }
                string text1 = "Add Key";
                if (flag3)
                {
                    genericMenu.AddDisabledItem(new GUIContent(text1));
                }
                else
                {
                    genericMenu.AddItem(new GUIContent(text1), false, new GenericMenu.MenuFunction2(this.AddKeysAtCurrentTime), (object)curvesAffectedByNodes1);
                }
                string text2 = "Delete Key";
                if (flag4)
                {
                    genericMenu.AddDisabledItem(new GUIContent(text2));
                }
                else
                {
                    genericMenu.AddItem(new GUIContent(text2), false, new GenericMenu.MenuFunction2(this.DeleteKeysAtCurrentTime), (object)curvesAffectedByNodes1);
                }
                if (!flag5)
                {
                    genericMenu.AddSeparator(string.Empty);
                    List <KeyIdentifier> keyIdentifierList = new List <KeyIdentifier>();
                    using (List <AnimationWindowCurve> .Enumerator enumerator = curvesAffectedByNodes1.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            AnimationWindowCurve current = enumerator.Current;
                            if (!current.isPPtrCurve)
                            {
                                int keyframeIndex = current.GetKeyframeIndex(this.state.time);
                                if (keyframeIndex != -1)
                                {
                                    CurveRenderer curveRenderer = CurveRendererCache.GetCurveRenderer(this.state.activeAnimationClip, current.binding);
                                    int           curveId       = CurveUtility.GetCurveID(this.state.activeAnimationClip, current.binding);
                                    keyIdentifierList.Add(new KeyIdentifier(curveRenderer, curveId, keyframeIndex));
                                }
                            }
                        }
                    }
                }
            }
            return(genericMenu);
        }