/// <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();
        }
    }
 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();
    }
    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;
    }
	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 ();
	}		
    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 ();
    }
    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;
    }
	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();
		};
	}
 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();
         }
     }
 }
Beispiel #11
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();
    }
    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();
    }
    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();
    }
    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();
    }
Beispiel #15
0
	void Selector(SerializedProperty property) {
		GenericMenu menu = new GenericMenu();
		AtlasAsset atlasAsset = (AtlasAsset)atlasProp.objectReferenceValue;
		Atlas atlas = atlasAsset.GetAtlas();
		FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic);
		List<AtlasRegion> regions = (List<AtlasRegion>)field.GetValue(atlas);

		for (int i = 0; i < regions.Count; i++) {
			string name = regions[i].name;
			menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
		}


		menu.ShowAsContext();
	}
Beispiel #16
0
        void OnCurveGUI(Rect rect, SerializedProperty curve, CurveState state)
        {
            // Discard invisible curves
            if (!state.visible)
            {
                return;
            }

            var animCurve = curve.animationCurveValue;
            var keys      = animCurve.keys;
            var length    = keys.Length;

            // Curve drawing
            // Slightly dim non-editable curves
            var color = state.color;

            if (!state.editable)
            {
                color.a *= 0.5f;
            }

            Handles.color = color;
            var bounds = settings.bounds;

            if (length == 0)
            {
                var p1 = CurveToCanvas(new Vector3(bounds.xMin, state.zeroKeyConstantValue));
                var p2 = CurveToCanvas(new Vector3(bounds.xMax, state.zeroKeyConstantValue));
                Handles.DrawAAPolyLine(state.width, p1, p2);
            }
            else if (length == 1)
            {
                var p1 = CurveToCanvas(new Vector3(bounds.xMin, keys[0].value));
                var p2 = CurveToCanvas(new Vector3(bounds.xMax, keys[0].value));
                Handles.DrawAAPolyLine(state.width, p1, p2);
            }
            else
            {
                var prevKey = keys[0];
                for (int k = 1; k < length; k++)
                {
                    var key = keys[k];
                    var pts = BezierSegment(prevKey, key);

                    if (float.IsInfinity(prevKey.outTangent) || float.IsInfinity(key.inTangent))
                    {
                        var s = HardSegment(prevKey, key);
                        Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]);
                    }
                    else
                    {
                        Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width);
                    }

                    prevKey = key;
                }

                // Curve extents & loops
                if (keys[0].time > bounds.xMin)
                {
                    if (state.loopInBounds)
                    {
                        var p1 = keys[length - 1];
                        p1.time -= settings.bounds.width;
                        var p2  = keys[0];
                        var pts = BezierSegment(p1, p2);

                        if (float.IsInfinity(p1.outTangent) || float.IsInfinity(p2.inTangent))
                        {
                            var s = HardSegment(p1, p2);
                            Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]);
                        }
                        else
                        {
                            Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width);
                        }
                    }
                    else
                    {
                        var p1 = CurveToCanvas(new Vector3(bounds.xMin, keys[0].value));
                        var p2 = CurveToCanvas(keys[0]);
                        Handles.DrawAAPolyLine(state.width, p1, p2);
                    }
                }

                if (keys[length - 1].time < bounds.xMax)
                {
                    if (state.loopInBounds)
                    {
                        var p1 = keys[length - 1];
                        var p2 = keys[0];
                        p2.time += settings.bounds.width;
                        var pts = BezierSegment(p1, p2);

                        if (float.IsInfinity(p1.outTangent) || float.IsInfinity(p2.inTangent))
                        {
                            var s = HardSegment(p1, p2);
                            Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]);
                        }
                        else
                        {
                            Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width);
                        }
                    }
                    else
                    {
                        var p1 = CurveToCanvas(keys[length - 1]);
                        var p2 = CurveToCanvas(new Vector3(bounds.xMax, keys[length - 1].value));
                        Handles.DrawAAPolyLine(state.width, p1, p2);
                    }
                }
            }

            // Make sure selection is correct (undo can break it)
            bool isCurrentlySelectedCurve = curve == m_SelectedCurve;

            if (isCurrentlySelectedCurve && m_SelectedKeyframeIndex >= length)
            {
                m_SelectedKeyframeIndex = -1;
            }

            // Handles & keys
            for (int k = 0; k < length; k++)
            {
                bool isCurrentlySelectedKeyframe = k == m_SelectedKeyframeIndex;
                var  e = Event.current;

                var pos     = CurveToCanvas(keys[k]);
                var hitRect = new Rect(pos.x - 8f, pos.y - 8f, 16f, 16f);
                var offset  = isCurrentlySelectedCurve
                    ? new RectOffset(5, 5, 5, 5)
                    : new RectOffset(6, 6, 6, 6);

                var outTangent        = pos + CurveTangentToCanvas(keys[k].outTangent).normalized * 40f;
                var inTangent         = pos - CurveTangentToCanvas(keys[k].inTangent).normalized * 40f;
                var inTangentHitRect  = new Rect(inTangent.x - 7f, inTangent.y - 7f, 14f, 14f);
                var outTangentHitrect = new Rect(outTangent.x - 7f, outTangent.y - 7f, 14f, 14f);

                // Draw
                if (state.showNonEditableHandles)
                {
                    if (e.type == EventType.repaint)
                    {
                        var selectedColor = (isCurrentlySelectedCurve && isCurrentlySelectedKeyframe)
                            ? settings.selectionColor
                            : state.color;

                        // Keyframe
                        EditorGUI.DrawRect(offset.Remove(hitRect), selectedColor);

                        // Tangents
                        if (isCurrentlySelectedCurve && (!state.onlyShowHandlesOnSelection || (state.onlyShowHandlesOnSelection && isCurrentlySelectedKeyframe)))
                        {
                            Handles.color = selectedColor;

                            if (k > 0 || state.loopInBounds)
                            {
                                Handles.DrawAAPolyLine(state.handleWidth, pos, inTangent);
                                EditorGUI.DrawRect(offset.Remove(inTangentHitRect), selectedColor);
                            }

                            if (k < length - 1 || state.loopInBounds)
                            {
                                Handles.DrawAAPolyLine(state.handleWidth, pos, outTangent);
                                EditorGUI.DrawRect(offset.Remove(outTangentHitrect), selectedColor);
                            }
                        }
                    }
                }

                // Events
                if (state.editable)
                {
                    // Keyframe move
                    if (m_EditMode == EditMode.Moving && e.type == EventType.MouseDrag && isCurrentlySelectedCurve && isCurrentlySelectedKeyframe)
                    {
                        EditMoveKeyframe(animCurve, keys, k);
                    }

                    // Tangent editing
                    if (m_EditMode == EditMode.TangentEdit && e.type == EventType.MouseDrag && isCurrentlySelectedCurve && isCurrentlySelectedKeyframe)
                    {
                        bool alreadyBroken = !(Mathf.Approximately(keys[k].inTangent, keys[k].outTangent) || (float.IsInfinity(keys[k].inTangent) && float.IsInfinity(keys[k].outTangent)));
                        EditMoveTangent(animCurve, keys, k, m_TangentEditMode, e.shift || !(alreadyBroken || e.control));
                    }

                    // Keyframe selection & context menu
                    if (e.type == EventType.mouseDown && rect.Contains(e.mousePosition))
                    {
                        if (hitRect.Contains(e.mousePosition))
                        {
                            if (e.button == 0)
                            {
                                SelectKeyframe(curve, k);
                                m_EditMode = EditMode.Moving;
                                e.Use();
                            }
                            else if (e.button == 1)
                            {
                                // Keyframe context menu
                                var menu = new GenericMenu();
                                menu.AddItem(new GUIContent("Delete Key"), false, (x) =>
                                {
                                    var action     = (MenuAction)x;
                                    var curveValue = action.curve.animationCurveValue;
                                    action.curve.serializedObject.Update();
                                    RemoveKeyframe(curveValue, action.index);
                                    m_SelectedKeyframeIndex = -1;
                                    SaveCurve(action.curve, curveValue);
                                    action.curve.serializedObject.ApplyModifiedProperties();
                                }, new MenuAction(curve, k));
                                menu.ShowAsContext();
                                e.Use();
                            }
                        }
                    }

                    // Tangent selection & edit mode
                    if (e.type == EventType.mouseDown && rect.Contains(e.mousePosition))
                    {
                        if (inTangentHitRect.Contains(e.mousePosition) && (k > 0 || state.loopInBounds))
                        {
                            SelectKeyframe(curve, k);
                            m_EditMode        = EditMode.TangentEdit;
                            m_TangentEditMode = Tangent.In;
                            e.Use();
                        }
                        else if (outTangentHitrect.Contains(e.mousePosition) && (k < length - 1 || state.loopInBounds))
                        {
                            SelectKeyframe(curve, k);
                            m_EditMode        = EditMode.TangentEdit;
                            m_TangentEditMode = Tangent.Out;
                            e.Use();
                        }
                    }

                    // Mouse up - clean up states
                    if (e.rawType == EventType.MouseUp && m_EditMode != EditMode.None)
                    {
                        m_EditMode = EditMode.None;
                    }

                    // Set cursors
                    {
                        EditorGUIUtility.AddCursorRect(hitRect, MouseCursor.MoveArrow);

                        if (k > 0 || state.loopInBounds)
                        {
                            EditorGUIUtility.AddCursorRect(inTangentHitRect, MouseCursor.RotateArrow);
                        }

                        if (k < length - 1 || state.loopInBounds)
                        {
                            EditorGUIUtility.AddCursorRect(outTangentHitrect, MouseCursor.RotateArrow);
                        }
                    }
                }
            }

            Handles.color = Color.white;
            SaveCurve(curve, animCurve);
        }
Beispiel #17
0
        // Handles mouse operations
        void InputEvents(Event e)
        {
            // Events
            mousePos = e.mousePosition;
            // Mouse Events
            Node clickedNode = null;

            if (e.type == EventType.MouseDown)
            {
                if (coreSystem != null && !EditorApplication.isPlaying)
                {
                    clickedNode = NodeAtPosition(mousePos);
                    if (clickedNode == null)
                    {
                        clickedConnector = ConAtPosition(mousePos);
                    }
                }


                if (clickedNode != null && !EditorApplication.isPlaying)
                {
                    // Click on a Node

                    if (e.button == 0)
                    {
                        // Left Click -> Window Drag. Handled by Unity
                    }
                    else if (e.button == 1)
                    {
                        if (clickedNode is StartAINode)
                        {
                        }
                        else
                        {
                            // Right click -> Node delete
                            customMenu.Call(ContextCallback, "Delete Node", "Duplicate Node");
                            e.Use();
                        }
                    }
                }
                else if (clickedConnector.active && !EditorApplication.isPlaying)
                {
                    // Click on Connector

                    // Store really clicked connector. Because clickedConnector might change below
                    reallyClickedConnector = clickedConnector.connector;

                    // Break old Connection(s) if there are some
                    if (clickedConnector.connector.connections.Count > 0)
                    {
                        Undo.RegisterCompleteObjectUndo(clickedConnector.connector, "Disconnect Nodes");
                        Connector otherConnector = clickedConnector.connector.Break();

                        if (otherConnector != null)
                        {
                            // The Curve Handle should now be detatched from Connector,
                            // And still be connected with the Connector on the other Node
                            clickedConnector = ConAtPosition(otherConnector.GetRect().center);
                        }
                    }
                }
                else
                {
                    // Click on empty Canvas (no Node, not sideWindow)
                    if (e.button == 2 || e.button == 0)
                    {
                        Rect rect = new Rect(sideWindow.opened ? position.width - 220 : position.width - 20, 0f, 220, position.height);

                        if (!rect.Contains(mousePos))
                        {
                            // Left/Middle Click -> Start scrolling
                            scrollWindow = true;
                            e.delta      = new Vector2(0, 0);
                        }
                    }
                    else if (e.button == 1)
                    {
                        if (SelectedObject != null && coreSystem == null)
                        {
                            CreateEasyAISystem();
                            EditorGUIUtility.ExitGUI();
                        }
                        // new menu system
                        // Now create the menu, add items and show it NEED TO CHANGE TO CUSTOM GENERIC MENU
                        GenericMenu menu = new GenericMenu();


                        //  no gameobject selected in scene
                        if (coreSystem == null)
                        {
                            menu.AddItem(new GUIContent("Create GameObject"), false, ContextCallback, "Create GameObject");
                        }
                        else
                        {
                            coreSystem.zoomFactor = 1f;

                            foreach (var item in nodes.Keys)
                            {
                                menu.AddItem(new GUIContent(item.ToString()), false, ContextCallback, item.ToString());
                            }
                        }

                        menu.ShowAsContext();
                        e.Use();


                        // Right click -> Editor Context Click
                        //customMenu.Call(ContextCallback, nodes.Keys.ToArray());
                        //e.Use ();
                    }
                }
            }
            else if (e.type == EventType.MouseUp)
            {
                // Left/Middle click up
                if (e.button == 2 || e.button == 0)
                {
                    // Connect 2 Nodes, if possible
                    if (clickedConnector.active)
                    {
                        ConHandle secondHandle = ConAtPosition(mousePos);
                        if (secondHandle.active)
                        {
                            if (clickedConnector.node != secondHandle.node)
                            {
                                // If Mouse Click and Release on the same Connector, connect them but don't record UNDO

                                if (secondHandle.connector != reallyClickedConnector)
                                {
                                    Undo.RegisterCompleteObjectUndo(clickedConnector.connector, "Connect Nodes");
                                    Undo.RegisterCompleteObjectUndo(secondHandle.connector, "Connect Nodes");
                                }

                                if (clickedConnector.connector.color == secondHandle.connector.color)
                                {
                                    // Connect both Connectors to each other.
                                    clickedConnector.connector.ConnectTo(secondHandle.connector);
                                }

                                // // RECALCULE NODES
                                //clickedConnector.node.CalculateNode();
                                //secondHandle.node.CalculateNode();
                            }
                        }
                        // // RECALCULE NODES
                        //if (clickedConnector.node != null) clickedConnector.node.CalculateNode();
                        //if (secondHandle.node != null) secondHandle.node.CalculateNode();
                        // recalcule all nodes ONLY FOR TEST
                        foreach (var item in coreSystem.nodes)
                        {
                            item.CalculateNode();
                        }
                    }


                    // Stop scrolling
                    clickedConnector.active = false;
                    scrollWindow            = false;
                }
            }
            else if (e.type == EventType.ScrollWheel)
            {
                if (e.delta.y > 1 && coreSystem.zoomFactor < 1f)
                {
                    coreSystem.zoomFactor = coreSystem.zoomFactor + 0.1f;
                }
                else if (e.delta.y < 0 && coreSystem.zoomFactor > 0.4f)
                {
                    coreSystem.zoomFactor = coreSystem.zoomFactor - 0.1f;
                }
            }


            // Scroll Mainwindow
            if (scrollWindow)
            {
                // Change Window and Nodes by Mouse delta (difference to last rendered position)
                scrollOffset += e.delta / 2;
                if (coreSystem != null)
                {
                    foreach (Node n in coreSystem.nodes)
                    {
                        n.rect.position += e.delta / 2;
                    }
                }
                //Repaint();
            }
        }
        private void HandleKeyHandlerGUI(GUIContent name, Utils.KeyHandler keyHandler, GUISkin skin)
        {
            const int keyButtonWidth = 90;

            GUILayout.BeginHorizontal();
            {
                keyHandler.Enable = GUI.Toggle(name,
                                               keyHandler.Enable,
                                               skin.button,
                                               GUI.Align(skin.label, TextAnchor.MiddleLeft),
                                               new GUILayoutOption[] { GUILayout.Width(ToggleButtonSize), GUILayout.Height(ToggleButtonSize) },
                                               new GUILayoutOption[] { GUILayout.Height(ToggleButtonSize) });
                GUILayout.FlexibleSpace();

                UnityEngine.GUI.enabled = keyHandler.Enable;

                for (int iKey = 0; iKey < keyHandler.NumKeyCodes; ++iKey)
                {
                    GUIContent buttonLabel = keyHandler.IsDetectingKey(iKey) ?
                                             GUI.MakeLabel("Detecting...") :
                                             GUI.MakeLabel(keyHandler.Keys[iKey].ToString());

                    bool toggleDetecting = GUILayout.Button(buttonLabel, skin.button, GUILayout.Width(keyButtonWidth), GUILayout.Height(ToggleButtonSize));
                    if (toggleDetecting)
                    {
                        keyHandler.DetectKey(this, !keyHandler.IsDetectingKey(iKey), iKey);
                    }
                }

                Rect dropDownButtonRect = new Rect();
                GUILayout.BeginVertical(GUILayout.Height(ToggleButtonSize));
                {
                    GUIStyle tmp = new GUIStyle(skin.button);
                    tmp.fontSize = 6;

                    m_showDropDown = GUILayout.Button(GUI.MakeLabel("v", true), tmp, GUILayout.Width(16), GUILayout.Height(14)) ?
                                     !m_showDropDown :
                                     m_showDropDown;
                    dropDownButtonRect = GUILayoutUtility.GetLastRect();
                    GUILayout.FlexibleSpace();
                }
                GUILayout.EndVertical();

                UnityEngine.GUI.enabled = true;

                if (m_showDropDown && dropDownButtonRect.Contains(Event.current.mousePosition))
                {
                    GenericMenu menu = new GenericMenu();
                    menu.AddItem(GUI.MakeLabel("Reset to default"), false, () =>
                    {
                        if (EditorUtility.DisplayDialog("Reset to default", "Reset key(s) to default?", "OK", "Cancel"))
                        {
                            keyHandler.ResetToDefault();
                        }
                    });
                    menu.AddItem(GUI.MakeLabel("Add key"), false, () =>
                    {
                        keyHandler.Add(KeyCode.None);
                    });

                    if (keyHandler.NumKeyCodes > 1)
                    {
                        menu.AddItem(GUI.MakeLabel("Remove key"), false, () =>
                        {
                            if (EditorUtility.DisplayDialog("Remove key", "Remove key: " + keyHandler[keyHandler.NumKeyCodes - 1].ToString() + "?", "OK", "Cancel"))
                            {
                                keyHandler.Remove(keyHandler.NumKeyCodes - 1);
                            }
                        });
                    }

                    menu.ShowAsContext();
                }
            }
            GUILayout.EndHorizontal();

            if (UnityEngine.GUI.changed)
            {
                EditorUtility.SetDirty(this);
            }
        }
Beispiel #19
0
        void OnGUI()
        {
            if (EditorApplication.isPlaying)
            {
                return;
            }
            if (!layerObject)
            {
                return;
            }
            layerObject.getRoot();//trigger lazy creation of the root object
            drawState.layerObject = layerObject;

            switch (Event.current.type)
            {
            case EventType.KeyDown:
            {
                if (Event.current.keyCode == KeyCode.Delete)
                {
                    if ((null != SelectedNode) && !(SelectedNode is RootNode))
                    {
                        Undo.RecordObject(layerObject, "Delete Node");
                        {
                            layerObject.nodes.Remove(SelectedNode);

                            foreach (var node in layerObject.nodes)
                            {
                                for (int i = 0; i < node.inputs.Count; i++)
                                {
                                    var nodeInput = node.inputs[i];
                                    if (nodeInput.inputNode == SelectedNode)
                                    {
                                        node.inputs.RemoveAt(i);
                                        i--;
                                    }
                                }
                            }
                        }
                        Undo.FlushUndoRecordObjects();

                        SelectedNode = null;
                        Event.current.Use();
                    }
                }
                break;
            }

            case EventType.MouseDown:
            {
                if (Event.current.button == 2)        //Middle mouse button
                {
                    drawState.scrollStart  = Event.current.mousePosition;
                    drawState.scrolling    = true;
                    drawState.scrollOffset = Vector2.zero;
                    Event.current.Use();
                }
                break;
            }

            case EventType.MouseUp:
            {
                if (Event.current.button == 2)        //Middle mouse button
                {
                    drawState.scrolling    = false;
                    drawState.guiOffset   += drawState.scrollOffset;
                    drawState.scrollOffset = Vector2.zero;
                    Event.current.Use();
                }
                break;
            }

            case EventType.MouseDrag:
            {
                if (drawState.scrolling)
                {
                    drawState.scrollOffset = Event.current.mousePosition - drawState.scrollStart;
                }
                break;
            }

            case EventType.ContextClick:
            {
                drawState.menuPos = Event.current.mousePosition;
                GenericMenu menu = new GenericMenu();

                foreach (Type type in Assembly.GetAssembly(typeof(RecipeLayerBase)).GetTypes()
                         .Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(BaseNode))))
                {
                    if (type != typeof(RootNode))
                    {
                        menu.AddItem(new GUIContent(Utilities.MakeNiceName(type.Name)), false, NodeCreateCallback, type);
                    }
                }

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

            if (null != SelectedNode)
            {
                if (!(SelectedNode is RootNode))
                {
                    SerializedObject nodeObject = new SerializedObject(SelectedNode);
                    var nameProp = nodeObject.FindProperty("nodeName");
                    nameProp.stringValue = DefaultNodeRenderer.DrawLabelEdit(SelectedNode, drawState, nameProp.stringValue);

                    nodeObject.ApplyModifiedProperties();
                }
            }

            {
                BeginWindows();

                if (Event.current.type == EventType.Layout)
                {
                    drawState.windowData.Clear();
                }
                int   id           = 0;
                Event currentEvent = Event.current;
                drawState.menuPos = currentEvent.mousePosition;

                foreach (var node in layerObject.nodes)
                {
                    BaseNodeRenderer.NodeDrawState.WindowData d = new BaseNodeRenderer.NodeDrawState.WindowData();
                    if (Event.current.type == EventType.Layout)
                    {
                        d.pos = node.nodePosition + drawState.guiOffset + drawState.scrollOffset;
                        drawState.windowData.Add(d);
                    }
                    else
                    {
                        d = drawState.windowData[id];
                    }

                    //update the window positions iff we are currently scrolling the view
                    if (drawState.scrolling && Event.current.type == EventType.MouseDrag)
                    {
                        d.pos = node.nodePosition + drawState.guiOffset + drawState.scrollOffset;
                        drawState.windowData[id] = d;
                    }

                    BaseNodeRenderer nodeRenderer = RendererFactory.getRenderer(node);

                    Rect             windowRect = new Rect(d.pos, nodeRenderer.getNodeSize(node).size);
                    SerializedObject nodeObject = new SerializedObject(node);
                    var posProp = nodeObject.FindProperty("nodePosition");

                    windowRect = GUI.Window(id, windowRect, DrawNodeWindow, "", GUIStyle.none);

                    posProp.vector2Value = windowRect.position - drawState.guiOffset - drawState.scrollOffset;

                    nodeObject.ApplyModifiedProperties();

                    id++;
                }

                EndWindows();//triggers the actual drawing of the windows, anything drawn after this will be drawn above all the windows
            }

            if (drawState.connectivityChange)
            {
                refreshShader = true;
                drawState.connectivityChange = false;
            }

            switch (Event.current.type)
            {
            case EventType.MouseUp:
            {
                drawState.drawCurve = false;
                break;
            }

            case EventType.Repaint:
            {
                foreach (var node in layerObject.nodes)
                {
                    BaseNodeRenderer nodeRenderer = RendererFactory.getRenderer(node);
                    var nodeSize = nodeRenderer.getNodeSize(node);

                    int i = 0;
                    foreach (var input in node.inputs)
                    {
                        if (null != input.inputNode)
                        {
                            var inputPos = node.nodePosition + new Vector2(0, (i * 16) + 35) + drawState.guiOffset + drawState.scrollOffset;
                            var endPos   = input.inputNode.nodePosition + new Vector2(nodeSize.width, 35 + (20 * input.outputIndex)) + drawState.guiOffset + drawState.scrollOffset;

                            DrawNodeCurve(inputPos, endPos, Color.cyan);
                        }
                        i++;
                    }
                }
                if (drawState.drawCurve)
                {
                    DrawNodeCurve(drawState.curveStart, Event.current.mousePosition, Color.red);
                }
                break;
            }
            }
        }
Beispiel #20
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 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 CreateList(SerializedProperty listProperty)
        {
            var list = new ReorderableList(listProperty.serializedObject, listProperty
                                           , true, true, true, true);

            list.headerHeight = HeaderHeight;
            list.footerHeight = FooterHeight;

            list.drawHeaderCallback = delegate(Rect rect)
            {
                EditorGUI.LabelField(rect, m_Settings.ListHeaderLabel);
            };

            list.elementHeight = m_Settings.ListElementHeight;

            list.drawElementCallback =
                delegate(Rect position, int index, bool isActive, bool isFocused)
            {
                var element = list.serializedProperty.GetArrayElementAtIndex(index);

                var typProp  = element.FindPropertyRelative(m_Settings.ItemTypePropName);
                var dataProp = element.FindPropertyRelative(m_Settings.ItemDataPropName);

                GUIContent label;
                GUIStyle   style = EditorStyles.label;

                if (typProp.enumValueIndex == -1)
                {
                    label = new GUIContent("Invalid Type", "Enum type value changed or removed?");
                    style = EditorGUIUtil.RedLabel;
                }
                else
                {
                    string vmessage = null;
                    var    vcheck   = m_Settings.Validate == null
                            ? PropertyValidationResult.Success
                            : m_Settings.Validate(dataProp, out vmessage);

                    label = new GUIContent(typProp.enumDisplayNames[typProp.enumValueIndex]);
                    if (!string.IsNullOrEmpty(vmessage))
                    {
                        label.tooltip = vmessage;
                    }

                    switch (vcheck)
                    {
                    case PropertyValidationResult.Warning:

                        style = EditorGUIUtil.YellowLabel;
                        break;

                    case PropertyValidationResult.Error:

                        style = EditorGUIUtil.RedLabel;
                        break;
                    }
                }

                var rect = new Rect(
                    position.x, position.y + EditorGUIUtility.standardVerticalSpacing,
                    position.width, position.height);

                m_Settings.DrawElement(rect, dataProp, label, style);
            };

            GenericMenu.MenuFunction2 addItem = delegate(object typValue)
            {
                list.index = AddItem(list.serializedProperty, (int)typValue);
            };

            GenericMenu.MenuFunction addAllItems = delegate()
            {
                var stdNames  = OutfitterEditorUtil.OutfitMaterialTypeNames;
                var stdValues = OutfitterEditorUtil.OutfitMaterialTypeTypeValues;

                var idx = list.serializedProperty.arraySize;

                for (int i = 0; i < stdNames.Length; i++)
                {
                    if (!IsInList(list.serializedProperty, stdValues[i]))
                    {
                        AddItem(list.serializedProperty, stdValues[i]);
                    }
                }

                list.index = idx;  // Assumes function is never called if list is full.
            };

            list.onAddDropdownCallback = delegate(Rect rect, ReorderableList roList)
            {
                var menu = new GenericMenu();

                var stdNames  = OutfitterEditorUtil.OutfitMaterialTypeNames;
                var stdValues = OutfitterEditorUtil.OutfitMaterialTypeTypeValues;

                for (int i = 0; i < stdNames.Length; i++)
                {
                    if (m_Settings.AllowMultipleTargets || !IsInList(list.serializedProperty, stdValues[i]))
                    {
                        menu.AddItem(new GUIContent(stdNames[i]), false, addItem, stdValues[i]);
                    }
                }

                if (menu.GetItemCount() == 0)
                {
                    menu.AddDisabledItem(new GUIContent("<None Available>"));
                }
                else
                {
                    menu.AddItem(new GUIContent("All"), false, addAllItems);
                }

                menu.ShowAsContext();
            };

            m_List = list;
        }
        protected override void OnInspectorDefaultGUI()
        {
            base.OnInspectorDefaultGUI();

            GUILayout.BeginHorizontal();
            EditorGUILayout.HelpBox("Entity Manager, Control all EntityLogic!", MessageType.Info);
            GUILayout.EndHorizontal();

            GUILayout.BeginVertical("Box");

            GUILayout.BeginHorizontal();
            GUILayout.Label("Define Entity", "BoldLabel");
            GUILayout.EndHorizontal();

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

                GUILayout.BeginHorizontal();
                GUILayout.Label("Type", GUILayout.Width(40));
                if (GUILayout.Button(Target.DefineEntityNames[i], "MiniPopup"))
                {
                    GenericMenu gm    = new GenericMenu();
                    List <Type> types = GlobalTools.GetTypesInRunTimeAssemblies();
                    for (int m = 0; m < types.Count; m++)
                    {
                        if (types[m].IsSubclassOf(typeof(EntityLogicBase)))
                        {
                            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();
                }
                if (GUILayout.Button("Delete", "Minibutton", GUILayout.Width(50)))
                {
                    Undo.RecordObject(target, "Delete Define Entity");
                    Target.DefineEntityNames.RemoveAt(i);
                    Target.DefineEntityTargets.RemoveAt(i);
                    HasChanged();
                    continue;
                }
                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", "Minibutton"))
            {
                Undo.RecordObject(target, "New Define Entity");
                Target.DefineEntityNames.Add("<None>");
                Target.DefineEntityTargets.Add(null);
                HasChanged();
            }
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();
        }
        /// <summary> Show a context menu for the graph. Shown when the developer right clicks over the grid area </summary>
        private void ShowGraphContextMenu()
        {
            var menu = new GenericMenu(); //create a generic menu

            var nodeMenus = new List <NodeMenuItem>();

            foreach (Type type in NodeTypes)
            {
                NodeMenu nodeMenu;
                string   path = GetNodeMenuName(type, out nodeMenu); //Get node context menu path
                if (string.IsNullOrEmpty(path))
                {
                    continue;                                      //empty entry means that the node will be hidden from the menu
                }
                nodeMenus.Add(new NodeMenuItem(nodeMenu, type));
            }

            nodeMenus = nodeMenus.OrderBy(n => n.Menu.Order).ThenBy(o => o.Menu.MenuName).ToList();

            string nodeRootPath = UILabels.CreateNode + "/";

            foreach (NodeMenuItem nodeMenuItem in nodeMenus)
            {
                NodeMenuItem menuItem = nodeMenuItem;
                if (menuItem.Menu.AddSeparatorBefore)
                {
                    menu.AddSeparator(nodeRootPath);
                }
                menu.AddItem(new GUIContent(nodeRootPath + menuItem.Menu.MenuName), false, () => ExecuteGraphAction(GraphAction.CreateNode, menuItem.NodeType.AssemblyQualifiedName)); //Create Node
                if (menuItem.Menu.AddSeparatorAfter)
                {
                    menu.AddSeparator(nodeRootPath);
                }
            }


//            foreach (Type type in NodeTypes)
//            {
//                NodeMenu nodeMenu;
//                string path = GetNodeMenuName(type, out nodeMenu); //Get node context menu path
//                if (string.IsNullOrEmpty(path)) continue; //empty entry means that the node will be hidden from the menu
//                Type nodeType = type;
//                menu.AddItem(new GUIContent(UILabels.Create + "/" + path), false, () => ExecuteGraphAction(GraphAction.CreateNode, nodeType.AssemblyQualifiedName)); //Create Node
//            }

            menu.AddSeparator("");
            var pasteNode = new GUIContent(UILabels.Paste);

            if (WindowSettings.CanPasteNodes)
            {
                menu.AddItem(pasteNode, false, () => { ExecuteGraphAction(GraphAction.Paste); }); //Paste Node
            }
            else
            {
                menu.AddDisabledItem(pasteNode); //Paste Node label
            }
            menu.AddSeparator("");
            if (WindowSettings.SelectedNodes.Count > 0)
            {
                menu.AddItem(new GUIContent(UILabels.CenterSelectedNodes), false, () => { CenterSelectedNodesInWindow(); }); //Center Selected Nodes
                menu.AddSeparator("");
            }

            menu.AddItem(new GUIContent(UILabels.Overview), false, () => { CenterAllNodesInWindow(); });                //Overview
            menu.AddItem(new GUIContent(UILabels.GoToStartNode), false, GoToStartOrEnterNode);                          //Go to Start Node
            menu.AddSeparator("");
            AddCustomContextMenuItems(menu, CurrentGraph);                                                              //Add custom menu options from graph
            menu.AddItem(new GUIContent(UILabels.Settings), false, () => { DoozyWindow.Open(DoozyWindow.View.Nody); }); //Settings
            menu.ShowAsContext();                                                                                       //show menu at mouse position
        }
Beispiel #25
0
        protected void DrawLanguages()
        {
            _languagesHelpRect = EditorHelper.ShowHideableHelpBox("GameFramework.LocalisationEditorWindow.Languages", "Here you can specify the languages for which you will provide localised values.\n\nYou should enter the language name and also an optional ISO-639-1 code for use with google translate if you want to perform automatic translations. For convenience Unity supported languages are available from the dropdown button at the bottom right.", _languagesHelpRect);
            EditorGUILayout.BeginVertical("Box");

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Name", GUILayout.ExpandWidth(true));
            EditorGUILayout.LabelField("Code", GUILayout.Width(60 + GuiStyles.RemoveButtonWidth + 6));
            //EditorGUILayout.LabelField("", GUILayout.Width(GuiStyles.RemoveButtonWidth));
            EditorGUILayout.EndHorizontal();

            serializedObject.Update();

            string languageForDeleting = null;

            for (var i = 0; i < _languagesProperty.arraySize; i++)
            {
                EditorGUILayout.BeginHorizontal();

                var languageProperty = _languagesProperty.GetArrayElementAtIndex(i);
                var nameProperty     = languageProperty.FindPropertyRelative("Name");
                EditorGUILayout.PropertyField(nameProperty, GUIContent.none, GUILayout.ExpandWidth(true));

                var codeProperty = languageProperty.FindPropertyRelative("Code");
                EditorGUILayout.PropertyField(codeProperty, GUIContent.none, GUILayout.Width(60));

                if (GUILayout.Button("-", EditorStyles.miniButton, GUILayout.Width(GuiStyles.RemoveButtonWidth)))
                {
                    languageForDeleting = nameProperty.stringValue;
                    break;
                }

                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.EndVertical();

            serializedObject.ApplyModifiedProperties();

            // add functionality
            EditorGUILayout.BeginHorizontal();
            _newLanguage = EditorGUILayout.TextField("", _newLanguage, GUILayout.ExpandWidth(true));
            if (string.IsNullOrEmpty(_newLanguage) || _targetLocalisationData.ContainsLanguage(_newLanguage))
            {
                GUI.enabled = false;
            }
            if (GUILayout.Button(new GUIContent("Add", "Add the specified language to the list"), EditorStyles.miniButton, GUILayout.Width(100)))
            {
                Undo.RecordObject(_targetLocalisationData, "Add Language");
                _targetLocalisationData.AddLanguage(_newLanguage);
                _targetChanged = true;
                _newLanguage   = "";
            }
            GUI.enabled = true;

            //if (GUILayout.Button(EditorGUIUtility.IconContent("Toolbar Plus More", "Add to list"), GUILayout.Width(25)))
            if (GUILayout.Button(new GUIContent("+", "Add a new language to the list"), EditorStyles.miniButton, GUILayout.Width(20)))
            {
                var menu = new GenericMenu();
                foreach (var languageDefinition in Languages.LanguageDefinitions)
                {
                    if (!_targetLocalisationData.ContainsLanguage(languageDefinition.Name))
                    {
                        menu.AddItem(new GUIContent(languageDefinition.Name + " (" + languageDefinition.Code + ")"), false, AddLanguage, languageDefinition.Name);
                    }
                }
                menu.ShowAsContext();
            }
            EditorGUILayout.EndHorizontal();

            // delay deleting to avoid editor issues.
            if (languageForDeleting != null &&
                EditorUtility.DisplayDialog("Delete Language?", string.Format("Are you sure you want to delete the language '{0}'?\n\nDeleting this language will also delete all translations for this language from the list of entries.", languageForDeleting), "Yes", "No"))
            {
                Undo.RecordObject(_targetLocalisationData, "Delete Language");
                _targetLocalisationData.RemoveLanguage(languageForDeleting);
                _targetChanged = true;
            }
        }
Beispiel #26
0
    void OnGUI()
    {
        Event e = Event.current;

        //trunk/branches
        //GUI.color = Color.white;
        //Dictionary<string, ProxyBool> fs = YangMenuHelper.helperIns.switchFloders;
        m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition);
        //if (NGUIEditorTools.DrawHeader("切换主分支", "切换主分支key"))
        //{
        //    NGUIEditorTools.BeginContents();
        //    int index = 0;
        //    foreach (var item in fs)//用复选框实现单选按钮
        //    {

        //        if (item.Value.m_bool != EditorGUILayout.ToggleLeft(item.Key, item.Value.m_bool))
        //        {
        //            if (!item.Value.m_bool)
        //            {
        //                UnityEngine.Debug.Log("item:" + item.Key + "  item.Value.m_bool:" + item.Value.m_bool);
        //                item.Value.m_bool = true;
        //                YangMenuHelper.helperIns.projMiniPath = item.Key;//选中.
        //                YangMenuHelper.helperIns.WriteConfigLine(0, "switchFloder.txt", "path=" + YangMenuHelper.helperIns.projMiniPath);
        //            }
        //        }
        //        else
        //        {
        //            //UnityEngine.Debug.Log(" false !!!item:" + item.Key + "  item.Value.m_bool:" + item.Value.m_bool);

        //            if (!item.Key.Equals(YangMenuHelper.helperIns.projMiniPath))
        //            {
        //                item.Value.m_bool = false;
        //            }
        //        }
        //        index++;
        //    }
        //    NGUIEditorTools.EndContents();
        //}
        //server list
        GUI.color = Color.white;
        Dictionary <ServerInfo, ProxyBool> serverf = YangMenuHelper.helperIns.serverFloders;

        if (NGUIEditorTools.DrawHeader("切换服务器", "切换服务器key"))
        {
            NGUIEditorTools.BeginContents();
            GUILayout.BeginHorizontal();
            bool selectSelf = YangMenuHelper.helperIns.currentServerIP.Equals(selfIP);
            if (selectSelf != EditorGUILayout.ToggleLeft(selfIP, selectSelf))
            {
                if (!string.IsNullOrEmpty(selfIP))
                {
                    YangMenuHelper.helperIns.currentServerIP = selfIP;
                    WriteIP();
                }
            }

            newSelfIp = GUILayout.TextField(newSelfIp, 25);
            if (GUILayout.Button("保存"))
            {
                if (!string.IsNullOrEmpty(newSelfIp) && !selfIP.Equals(newSelfIp) && YangMenuHelper.helperIns.IsIP(newSelfIp))
                {
                    selfIP = newSelfIp;

                    YangMenuHelper.helperIns.WriteConfigLine(0, "temp/selfIp.txt", selfIP);
                }
            }
            GUILayout.EndHorizontal();

            int index = 0;
            foreach (var item in serverf)//用复选框实现单选按钮
            {
                if (item.Key.connectioned)
                {
                    GUI.color = Color.green;
                }
                else
                {
                    GUI.color = Color.red;
                }
                if (item.Value.m_bool != EditorGUILayout.ToggleLeft(item.Key.content + ":" + (item.Key.connectioned ? "已开" : "未开"), item.Value.m_bool))
                {
                    if (!item.Value.m_bool)
                    {
                        UnityEngine.Debug.Log("item:" + item.Key + "  item.Value.m_bool:" + item.Value.m_bool);
                        item.Value.m_bool = true;
                        YangMenuHelper.helperIns.currentServerIP = item.Key.ip;//选中.
                        WriteIP();
                    }
                }
                else
                {
                    if (!item.Key.ip.Equals(YangMenuHelper.helperIns.currentServerIP))
                    {
                        item.Value.m_bool = false;
                    }
                }
                index++;
            }

            NGUIEditorTools.EndContents();
        }
        //log level
        GUI.color = Color.white;
        Dictionary <int, LineConfigInfo> clientConfig = YangMenuHelper.helperIns.ywindow_clientConfigBean.configDic;

        if (NGUIEditorTools.DrawHeader("修改ClientConfig", "修改ClientConfigkey"))
        {
            NGUIEditorTools.BeginContents();
            foreach (var item in clientConfig)//用复选框实现单选按钮
            {
                if (item.Value.myType == CONFIG_TYPE.STRING || item.Value.myType == CONFIG_TYPE.BOOL)
                {
                    if (GUILayout.Button(item.Value.lineValue))
                    {
                        if (item.Value.myType == CONFIG_TYPE.STRING)
                        {
                            GenericMenu menu = new GenericMenu();
                            for (int i = 0; i < item.Value.lineValues.Count; i++)
                            {
                                menu.AddItem(new GUIContent(item.Value.lineValues[i]), false, StringChangeCallBack, new object[] { item.Value, item.Value.lineValues[i] });
                            }
                            menu.ShowAsContext();
                        }
                        else
                        {
                            item.Value.OnBoolChange();
                        }
                    }
                }
                else if (item.Value.myType == CONFIG_TYPE.INT || item.Value.myType == CONFIG_TYPE.INPUT)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Label(item.Value.lineValue);
                    item.Value.xmlValue = GUILayout.TextField(item.Value.xmlValue, 25);

                    if (GUILayout.Button("更改"))
                    {
                        item.Value.OnInputChange();
                    }

                    GUILayout.EndHorizontal();
                }
            }
            //ButtonCtrl layoutBtn = new ButtonCtrl();
            //layoutBtn.Caption = "操作区布局";
            //layoutBtn.Name = "LayoutButton";
            //layoutBtn.Size = btnRect;
            //layoutBtn.onClick = OnLayoutBtnClick;
            NGUIEditorTools.EndContents();
        }
        EditorGUILayout.EndScrollView();
    }
    /// <summary>
    /// Update and Draw the inspector
    /// </summary>
    public override void OnInspectorGUI()
    {
        eventTrack.Update();
        ActorItemTrack track = base.serializedObject.targetObject as ActorItemTrack;

        CinemaActorAction[] actions     = track.ActorActions;
        CinemaActorEvent[]  actorEvents = track.ActorEvents;

        if (actions.Length > 0 || actorEvents.Length > 0)
        {
            actionFoldout = EditorGUILayout.Foldout(actionFoldout, actionContent);
            if (actionFoldout)
            {
                EditorGUI.indentLevel++;

                for (int i = 0; i < actions.Length; i++)
                {
                    EditorGUILayout.ObjectField(actions[i].name, actions[i], typeof(CinemaActorAction), true);
                }
                for (int i = 0; i < actorEvents.Length; i++)
                {
                    EditorGUILayout.ObjectField(actorEvents[i].name, actorEvents[i], typeof(CinemaActorEvent), true);
                }
                EditorGUI.indentLevel--;
            }
        }

        if (GUILayout.Button(addActionContent))
        {
            GenericMenu createMenu = new GenericMenu();

            Type   actorActionType = typeof(CinemaActorAction);
            Type[] actionSubTypes  = DirectorHelper.GetAllSubTypes(actorActionType);
            for (int i = 0; i < actionSubTypes.Length; i++)
            {
                string text     = string.Empty;
                string category = string.Empty;
                string label    = string.Empty;
                foreach (CutsceneItemAttribute attribute in actionSubTypes[i].GetCustomAttributes(typeof(CutsceneItemAttribute), true))
                {
                    if (attribute != null)
                    {
                        category = attribute.Category;
                        label    = attribute.Label;
                        text     = string.Format("{0}/{1}", category, label);
                        break;
                    }
                }
                ContextData userData = new ContextData {
                    type = actionSubTypes[i], label = label, category = category
                };
                createMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction2(AddEvent), userData);
            }

            Type   actorEventType = typeof(CinemaActorEvent);
            Type[] eventSubTypes  = DirectorHelper.GetAllSubTypes(actorEventType);
            for (int i = 0; i < eventSubTypes.Length; i++)
            {
                string text     = string.Empty;
                string category = string.Empty;
                string label    = string.Empty;
                foreach (CutsceneItemAttribute attribute in eventSubTypes[i].GetCustomAttributes(typeof(CutsceneItemAttribute), true))
                {
                    if (attribute != null)
                    {
                        category = attribute.Category;
                        label    = attribute.Label;
                        text     = string.Format("{0}/{1}", attribute.Category, attribute.Label);
                        break;
                    }
                }
                ContextData userData = new ContextData {
                    type = eventSubTypes[i], label = label, category = category
                };
                createMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction2(AddEvent), userData);
            }
            createMenu.ShowAsContext();
        }

        eventTrack.ApplyModifiedProperties();
    }
Beispiel #28
0
        /// <summary>
        /// Processes input events
        /// </summary>
        public static void InputEvents()
        {
            Event e = Event.current;

            mousePos = e.mousePosition;

            bool leftClick = e.button == 0, rightClick = e.button == 1,
                 mouseDown = e.type == EventType.MouseDown, mousUp = e.type == EventType.MouseUp;

            if (ignoreInput(mousePos))
            {
                return;
            }

            #region Change Node selection and focus
            // Choose focused and selected Node, accounting for focus changes
            curEditorState.focusedNode = null;
            if (mouseDown || mousUp)
            {
                curEditorState.focusedNode = NodeEditor.NodeAtPosition(mousePos);
                if (curEditorState.focusedNode != curEditorState.selectedNode)
                {
                    unfocusControls = true;
                }
                if (mouseDown && leftClick)
                {
                    curEditorState.selectedNode = curEditorState.focusedNode;
                    RepaintClients();
                }
            }
            // Perform above mentioned focus changes in Repaint, which is the only suitable time to do this
            if (unfocusControls && Event.current.type == EventType.Repaint)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;
                unfocusControls            = false;
            }
                #if UNITY_EDITOR
            if (curEditorState.focusedNode != null)
            {
                UnityEditor.Selection.activeObject = curEditorState.focusedNode;
            }
                #endif
            #endregion

            switch (e.type)
            {
            case EventType.MouseDown:

                curEditorState.dragNode  = false;
                curEditorState.panWindow = false;

                if (curEditorState.focusedNode != null)
                {                 // Clicked a Node
                    if (rightClick)
                    {             // Node Context Click
                        GenericMenu menu = new GenericMenu();
                        menu.AddItem(new GUIContent("Delete Node"), false, ContextCallback, new NodeEditorMenuCallback("deleteNode", curNodeCanvas, curEditorState));
                        menu.AddItem(new GUIContent("Duplicate Node"), false, ContextCallback, new NodeEditorMenuCallback("duplicateNode", curNodeCanvas, curEditorState));
                        if (curEditorState.focusedNode.AcceptsTranstitions)
                        {
                            menu.AddSeparator("Seperator");
                            menu.AddItem(new GUIContent("Make Transition"), false, ContextCallback, new NodeEditorMenuCallback("startTransition", curNodeCanvas, curEditorState));
                        }
                        menu.ShowAsContext();
                        e.Use();
                    }
                    else if (leftClick)
                    {                     // Detect click on a connection knob
                        if (!CanvasGUIToScreenRect(curEditorState.focusedNode.rect).Contains(mousePos))
                        {                 // Clicked NodeEdge, check Node Inputs and Outputs
                            NodeOutput nodeOutput = curEditorState.focusedNode.GetOutputAtPos(e.mousePosition);
                            if (nodeOutput != null)
                            {                             // Output clicked -> New Connection drawn from this
                                curEditorState.connectOutput = nodeOutput;
                                e.Use();
                                return;
                            }

                            NodeInput nodeInput = curEditorState.focusedNode.GetInputAtPos(e.mousePosition);
                            if (nodeInput != null && nodeInput.connection != null)
                            {                             // Input clicked -> Loose and edit Connection
                                // TODO: Draw input from NodeInput
                                curEditorState.connectOutput = nodeInput.connection;
                                nodeInput.RemoveConnection();
                                e.Use();
                            }
                        }
                    }
                }
                else
                {                 // Clicked on canvas
                    // NOTE: Panning is not done here but in LateEvents, so buttons on the canvas won't be blocked when clicking

                    if (rightClick)
                    {                     // Editor Context Click
                        GenericMenu menu = new GenericMenu();
                        if (curEditorState.connectOutput != null)
                        {                         // A connection is drawn, so provide a context menu with apropriate nodes to auto-connect
                            foreach (Node node in NodeTypes.nodes.Keys)
                            {                     // Iterate through all nodes and check for compability
                                foreach (NodeInput input in node.Inputs)
                                {
                                    if (input.type == curEditorState.connectOutput.type)
                                    {
                                        menu.AddItem(new GUIContent("Add " + NodeTypes.nodes[node].adress), false, ContextCallback, new NodeEditorMenuCallback(node.GetID, curNodeCanvas, curEditorState));
                                        break;
                                    }
                                }
                            }
                        }
                        else if (curEditorState.makeTransition != null && curEditorState.makeTransition.AcceptsTranstitions)
                        {                         // A transition is drawn, so provide a context menu with nodes to auto-connect
                            foreach (Node node in NodeTypes.nodes.Keys)
                            {                     // Iterate through all nodes and check for compability
                                if (node.AcceptsTranstitions)
                                {
                                    menu.AddItem(new GUIContent("Add " + NodeTypes.nodes[node].adress), false, ContextCallback, new NodeEditorMenuCallback(node.GetID, curNodeCanvas, curEditorState));
                                }
                            }
                        }
                        else
                        {                         // Ordinary context click, add all nodes to add
                            foreach (Node node in NodeTypes.nodes.Keys)
                            {
                                menu.AddItem(new GUIContent("Add " + NodeTypes.nodes [node].adress), false, ContextCallback, new NodeEditorMenuCallback(node.GetID, curNodeCanvas, curEditorState));
                            }
                        }
                        menu.ShowAsContext();
                        e.Use();
                    }
                }

                break;

            case EventType.MouseUp:

                if (curEditorState.focusedNode != null && curEditorState.connectOutput != null)
                {                 // Apply Drawn connections on node if theres a clicked input
                    if (!curEditorState.focusedNode.Outputs.Contains(curEditorState.connectOutput))
                    {             // An input was clicked, it'll will now be connected
                        NodeInput clickedInput = curEditorState.focusedNode.GetInputAtPos(e.mousePosition);
                        if (clickedInput.CanApplyConnection(curEditorState.connectOutput))
                        {                         // It can connect (type is equals, it does not cause recursion, ...)
                            clickedInput.ApplyConnection(curEditorState.connectOutput);
                        }
                    }
                    e.Use();
                }

                curEditorState.makeTransition = null;
                curEditorState.connectOutput  = null;
                curEditorState.dragNode       = false;
                curEditorState.panWindow      = false;

                break;

            case EventType.ScrollWheel:

                // Apply Zoom
                curEditorState.zoom = (float)Math.Round(Math.Min(2.0f, Math.Max(0.6f, curEditorState.zoom + e.delta.y / 15)), 2);

                RepaintClients();
                break;

            case EventType.KeyDown:

                // TODO: Node Editor: Shortcuts

                if (e.keyCode == KeyCode.N)                 // Start Navigating (curve to origin / active Node)
                {
                    curEditorState.navigate = true;
                }

                if (e.keyCode == KeyCode.LeftControl && curEditorState.selectedNode != null)
                {                 // Snap selected Node's position to multiples of 10
                    Vector2 pos = curEditorState.selectedNode.rect.position;
                    pos = (pos - curEditorState.panOffset) / 10;
                    pos = new Vector2(Mathf.RoundToInt(pos.x), Mathf.RoundToInt(pos.y));
                    curEditorState.selectedNode.rect.position = pos * 10 + curEditorState.panOffset;
                }

                RepaintClients();
                break;

            case EventType.KeyUp:

                if (e.keyCode == KeyCode.N)                 // Stop Navigating
                {
                    curEditorState.navigate = false;
                }

                RepaintClients();
                break;

            case EventType.MouseDrag:

                if (curEditorState.panWindow)
                {                 // Scroll everything with the current mouse delta
                    curEditorState.panOffset += e.delta * curEditorState.zoom;
                    foreach (Node node in curNodeCanvas.nodes)
                    {
                        node.rect.position += e.delta * curEditorState.zoom;
                    }
                    e.delta = Vector2.zero;
                    RepaintClients();
                }

                if (curEditorState.dragNode && curEditorState.selectedNode != null && GUIUtility.hotControl == 0)
                {                 // Drag the active node with the current mouse delta
                    curEditorState.selectedNode.rect.position += e.delta * curEditorState.zoom;
                    NodeEditorCallbacks.IssueOnMoveNode(curEditorState.selectedNode);
                    e.delta = Vector2.zero;
                    RepaintClients();
                }
                else
                {
                    curEditorState.dragNode = false;
                }

                break;
            }
        }
Beispiel #29
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();
	}
Beispiel #30
0
        private void InitReorderedList()
        {
            if (prefEntryHolder == null)
            {
                var tmp = Resources.FindObjectsOfTypeAll <PreferenceEntryHolder>();
                if (tmp.Length > 0)
                {
                    prefEntryHolder = tmp[0];
                }
                else
                {
                    prefEntryHolder = ScriptableObject.CreateInstance <PreferenceEntryHolder>();
                }
            }

            if (serializedObject == null)
            {
                serializedObject = new SerializedObject(prefEntryHolder);
            }

            userDefList  = new ReorderableList(serializedObject, serializedObject.FindProperty("userDefList"), false, true, true, true);
            unityDefList = new ReorderableList(serializedObject, serializedObject.FindProperty("unityDefList"), false, true, false, false);

            relSpliterPos = EditorPrefs.GetFloat("BGTools.PlayerPrefsEditor.RelativeSpliterPosition", 100 / position.width);

            userDefList.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, "User defined");
            };
            userDefList.drawElementBackgroundCallback = OnDrawElementBackgroundCallback;
            userDefList.drawElementCallback           = (Rect rect, int index, bool isActive, bool isFocused) =>
            {
                SerializedProperty element = GetUserDefListElementAtIndex(index, userDefList.serializedProperty);

                SerializedProperty key  = element.FindPropertyRelative("m_key");
                SerializedProperty type = element.FindPropertyRelative("m_typeSelection");

                SerializedProperty value;

                // Load only necessary type
                switch ((PreferenceEntry.PrefTypes)type.enumValueIndex)
                {
                case PreferenceEntry.PrefTypes.Float:
                    value = element.FindPropertyRelative("m_floatValue");
                    break;

                case PreferenceEntry.PrefTypes.Int:
                    value = element.FindPropertyRelative("m_intValue");
                    break;

                case PreferenceEntry.PrefTypes.String:
                    value = element.FindPropertyRelative("m_strValue");
                    break;

                default:
                    value = element.FindPropertyRelative("This should never happen");
                    break;
                }

                float spliterPos = relSpliterPos * rect.width;
                rect.y += 2;

                EditorGUI.BeginChangeCheck();
                string prefKeyName = key.stringValue;
                EditorGUI.LabelField(new Rect(rect.x, rect.y, spliterPos - 1, EditorGUIUtility.singleLineHeight), new GUIContent(prefKeyName, prefKeyName));
                GUI.enabled = false;
                EditorGUI.EnumPopup(new Rect(rect.x + spliterPos + 1, rect.y, 60, EditorGUIUtility.singleLineHeight), (PreferenceEntry.PrefTypes)type.enumValueIndex);
                GUI.enabled = !showLoadingIndicatorOverlay;
                switch ((PreferenceEntry.PrefTypes)type.enumValueIndex)
                {
                case PreferenceEntry.PrefTypes.Float:
                    EditorGUI.DelayedFloatField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), value, GUIContent.none);
                    break;

                case PreferenceEntry.PrefTypes.Int:
                    EditorGUI.DelayedIntField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), value, GUIContent.none);
                    break;

                case PreferenceEntry.PrefTypes.String:
                    EditorGUI.DelayedTextField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), value, GUIContent.none);
                    break;
                }
                if (EditorGUI.EndChangeCheck())
                {
                    entryAccessor.IgnoreNextChange();

                    switch ((PreferenceEntry.PrefTypes)type.enumValueIndex)
                    {
                    case PreferenceEntry.PrefTypes.Float:
                        PlayerPrefs.SetFloat(key.stringValue, value.floatValue);
                        break;

                    case PreferenceEntry.PrefTypes.Int:
                        PlayerPrefs.SetInt(key.stringValue, value.intValue);
                        break;

                    case PreferenceEntry.PrefTypes.String:
                        PlayerPrefs.SetString(key.stringValue, value.stringValue);
                        break;
                    }

                    PlayerPrefs.Save();
                }
            };
            userDefList.onRemoveCallback = (ReorderableList l) =>
            {
                userDefList.ReleaseKeyboardFocus();
                unityDefList.ReleaseKeyboardFocus();

                string prefKey = l.serializedProperty.GetArrayElementAtIndex(l.index).FindPropertyRelative("m_key").stringValue;
                if (EditorUtility.DisplayDialog("Warning!", $"Are you sure you want to delete this entry from PlayerPrefs?\n\nEntry: {prefKey}", "Yes", "No"))
                {
                    entryAccessor.IgnoreNextChange();

                    PlayerPrefs.DeleteKey(prefKey);
                    PlayerPrefs.Save();

                    ReorderableList.defaultBehaviours.DoRemoveButton(l);
                    PrepareData();
                    GUIUtility.ExitGUI();
                }
            };
            userDefList.onAddDropdownCallback = (Rect buttonRect, ReorderableList l) =>
            {
                var menu = new GenericMenu();
                foreach (PreferenceEntry.PrefTypes type in Enum.GetValues(typeof(PreferenceEntry.PrefTypes)))
                {
                    menu.AddItem(new GUIContent(type.ToString()), false, () =>
                    {
                        TextFieldDialog.OpenDialog("Create new property", "Key for the new property:", prefKeyValidatorList, (key) => {
                            entryAccessor.IgnoreNextChange();

                            switch (type)
                            {
                            case PreferenceEntry.PrefTypes.Float:
                                PlayerPrefs.SetFloat(key, 0.0f);

                                break;

                            case PreferenceEntry.PrefTypes.Int:
                                PlayerPrefs.SetInt(key, 0);

                                break;

                            case PreferenceEntry.PrefTypes.String:
                                PlayerPrefs.SetString(key, string.Empty);

                                break;
                            }
                            PlayerPrefs.Save();

                            PrepareData();

                            Focus();
                        }, this);
                    });
                }
                menu.ShowAsContext();
            };

            unityDefList.drawElementBackgroundCallback = OnDrawElementBackgroundCallback;
            unityDefList.drawElementCallback           = (Rect rect, int index, bool isActive, bool isFocused) =>
            {
                var element             = unityDefList.serializedProperty.GetArrayElementAtIndex(index);
                SerializedProperty key  = element.FindPropertyRelative("m_key");
                SerializedProperty type = element.FindPropertyRelative("m_typeSelection");

                SerializedProperty value;

                // Load only necessary type
                switch ((PreferenceEntry.PrefTypes)type.enumValueIndex)
                {
                case PreferenceEntry.PrefTypes.Float:
                    value = element.FindPropertyRelative("m_floatValue");
                    break;

                case PreferenceEntry.PrefTypes.Int:
                    value = element.FindPropertyRelative("m_intValue");
                    break;

                case PreferenceEntry.PrefTypes.String:
                    value = element.FindPropertyRelative("m_strValue");
                    break;

                default:
                    value = element.FindPropertyRelative("This should never happen");
                    break;
                }

                float spliterPos = relSpliterPos * rect.width;
                rect.y += 2;

                GUI.enabled = false;
                string prefKeyName = key.stringValue;
                EditorGUI.LabelField(new Rect(rect.x, rect.y, spliterPos - 1, EditorGUIUtility.singleLineHeight), new GUIContent(prefKeyName, prefKeyName));
                EditorGUI.EnumPopup(new Rect(rect.x + spliterPos + 1, rect.y, 60, EditorGUIUtility.singleLineHeight), (PreferenceEntry.PrefTypes)type.enumValueIndex);

                switch ((PreferenceEntry.PrefTypes)type.enumValueIndex)
                {
                case PreferenceEntry.PrefTypes.Float:
                    EditorGUI.DelayedFloatField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), value, GUIContent.none);
                    break;

                case PreferenceEntry.PrefTypes.Int:
                    EditorGUI.DelayedIntField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), value, GUIContent.none);
                    break;

                case PreferenceEntry.PrefTypes.String:
                    EditorGUI.DelayedTextField(new Rect(rect.x + spliterPos + 62, rect.y, rect.width - spliterPos - 60, EditorGUIUtility.singleLineHeight), value, GUIContent.none);
                    break;
                }
                GUI.enabled = !showLoadingIndicatorOverlay;
            };
            unityDefList.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, "Unity defined");
            };
        }
Beispiel #31
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();
	}
Beispiel #32
0
        /**
         *      retrieve mouse events for this node in this GraphEditor window.
         */
        private void HandleNodeMouseEvent()
        {
            switch (Event.current.type)
            {
            /*
             *              handling release of mouse drag from this node to another node.
             *              this node doesn't know about where the other node is. the master only knows.
             *              only emit event.
             */
            case EventType.Ignore: {
                NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_CONNECTING_END, this, Event.current.mousePosition, null));
                break;
            }

            /*
             *      check if the mouse-down point is over one of the connectionPoint in this node.
             *      then emit event.
             */
            case EventType.MouseDown: {
                Model.ConnectionPointData result = IsOverConnectionPoint(Event.current.mousePosition);

                if (result != null)
                {
                    NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_CONNECTING_BEGIN, this, Event.current.mousePosition, result));
                    break;
                }
                else
                {
                    NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_CLICKED,
                                                                  this, Event.current.mousePosition, null));
                }
                break;
            }
            }

            /*
             *      retrieve mouse events for this node in|out of this GraphTool window.
             */
            switch (Event.current.rawType)
            {
            case EventType.MouseUp: {
                bool eventSent = false;
                // send EVENT_CONNECTION_ESTABLISHED event if MouseUp performed on ConnectionPoint
                Action <Model.ConnectionPointData> raiseEventIfHit = (Model.ConnectionPointData point) => {
                    // Only one connectionPoint can send NodeEvent.
                    if (eventSent)
                    {
                        return;
                    }

                    // If InputConnectionPoint is not valid at this moment, ignore
                    if (!IsValidInputConnectionPoint(point))
                    {
                        return;
                    }

                    if (point.Region.Contains(Event.current.mousePosition))
                    {
                        NodeGUIUtility.NodeEventHandler(
                            new NodeEvent(NodeEvent.EventType.EVENT_CONNECTION_ESTABLISHED,
                                          this, Event.current.mousePosition, point));
                        eventSent = true;
                        return;
                    }
                };
                m_data.InputPoints.ForEach(raiseEventIfHit);
                m_data.OutputPoints.ForEach(raiseEventIfHit);
                break;
            }
            }

            /*
             *      right click to open Context menu
             */
            if (Event.current.type == EventType.ContextClick || (Event.current.type == EventType.MouseUp && Event.current.button == 1))
            {
                var menu = new GenericMenu();

                Data.Operation.Object.OnContextMenuGUI(menu);

                menu.AddItem(
                    new GUIContent("Delete"),
                    false,
                    () => {
                    NodeGUIUtility.NodeEventHandler(new NodeEvent(NodeEvent.EventType.EVENT_NODE_DELETE, this, Vector2.zero, null));
                }
                    );
                menu.ShowAsContext();
                Event.current.Use();
            }
        }
	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();
	}
        public bool DoProperty(Rect position, SerializedProperty property)
        {
            if (!reorderableListDict.ContainsKey(property.propertyPath))
            {
                return(false);
            }

            headerPosition        = new Rect(position);
            headerPosition.height = EditorGUIUtility.singleLineHeight;
            // Draw the background
            if (DrawBackgroundCallback != null)
            {
                Rect backgroundPosition = new Rect(headerPosition);
                backgroundPosition.xMin += EasyGUI.Indent;
                if (property.isExpanded)
                {
                    backgroundPosition.yMax += 15;
                }
                EditorGUI.DrawRect(backgroundPosition, DrawBackgroundCallback(false, false));
            }

            // Draw header
            if (HeaderCallback != null)
            {
                HeaderCallback(headerPosition);
            }
            else
            {
                string headerName = string.Format(HeaderStr, property.displayName, property.arraySize);
                EditorGUI.PropertyField(headerPosition, property, new GUIContent(headerName), false);
            }

            // Draw the reorderable list for the property
            if (property.isExpanded)
            {
                EditorGUI.BeginDisabledGroup(!Editable);
                if (!property.editable)
                {
                    EditorGUI.indentLevel++;
                }
                EditorGUI.BeginChangeCheck();
                var sizePosition = new Rect(headerPosition);
                sizePosition.yMin   = headerPosition.yMax;
                sizePosition.height = EditorGUIUtility.singleLineHeight;
                var newArraySize = Mathf.Clamp(EditorGUI.IntField(sizePosition, SizeStr, property.arraySize), 0, int.MaxValue);
                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RecordObject(property.serializedObject.targetObject, SetArraySizeStr);
                    property.arraySize = newArraySize;
                    EditorUtility.SetDirty(property.serializedObject.targetObject);
                }
                var listPosition = new Rect(sizePosition);
                listPosition.xMin += EasyGUI.Indent;
                listPosition.yMin  = sizePosition.yMax;
                var indentLevel = EditorGUI.indentLevel;
                EditorGUI.indentLevel = 0;
                reorderableListDict[property.propertyPath].DoList(listPosition);
                EditorGUI.indentLevel = indentLevel;
                if (!property.editable)
                {
                    EditorGUI.indentLevel--;
                }
                EditorGUI.EndDisabledGroup();
            }

            // Do dropdown menu for the header
            if (property.isArray && Event.current.type == EventType.MouseDown && headerPosition.Contains(Event.current.mousePosition))
            {
                GenericMenu popupMenu = new GenericMenu();
                if (HeaderMenuCallback != null && HeaderMenuCallback(popupMenu))
                {
                    Event.current.Use();
                    if (popupMenu.GetItemCount() != 0)
                    {
                        popupMenu.ShowAsContext();
                    }
                }
            }

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

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

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

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

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

                            SerializedProperty target = property.GetArrayElementAtIndex(newIndex);
                            target.objectReferenceInstanceIDValue = draggedObject.GetInstanceID();
                        }
                    }
                    evt.Use();
                }
            }

            return(true);
        }
    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();
    }
Beispiel #36
0
        public void DrawConnection(List <Node> nodes, Dictionary <string, List <string> > throughputListDict)
        {
            var startNodes = nodes.Where(node => node.nodeId == startNodeId).ToList();

            if (!startNodes.Any())
            {
                return;
            }

            var start = startNodes[0].GlobalConnectionPointPosition(outputPoint);

            start = Node.ScaleEffect(start);
            var startV3 = new Vector3(start.x, start.y, 0f);

            var endNodes = nodes.Where(node => node.nodeId == endNodeId).ToList();

            if (!endNodes.Any())
            {
                return;
            }

            var end = endNodes[0].GlobalConnectionPointPosition(inputPoint);

            end = Node.ScaleEffect(end);
            var endV3 = new Vector3(end.x, end.y + 1f, 0f);

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

            var pointDistance = (end.x - start.x) / 3f;

            if (pointDistance < AssetGraphGUISettings.CONNECTION_CURVE_LENGTH)
            {
                pointDistance = AssetGraphGUISettings.CONNECTION_CURVE_LENGTH;
            }

            var startTan = new Vector3(start.x + pointDistance, start.y, 0f);
            var endTan   = new Vector3(end.x - pointDistance, end.y, 0f);

            Handles.DrawBezier(startV3, endV3, startTan, endTan, Color.gray, null, 4f);

            // draw connection label if connection's label is not normal.
            if (Node.scaleFactor == Node.SCALE_MAX)
            {
                switch (label)
                {
                case AssetGraphSettings.DEFAULT_OUTPUTPOINT_LABEL: {
                    // show nothing
                    break;
                }

                case AssetGraphSettings.BUNDLIZER_BUNDLE_OUTPUTPOINT_LABEL: {
                    var labelPointV3 = new Vector3(centerPointV3.x - ((AssetGraphSettings.BUNDLIZER_BUNDLE_OUTPUTPOINT_LABEL.Length * 6f) / 2), centerPointV3.y - 24f, 0f);
                    Handles.Label(labelPointV3, AssetGraphSettings.BUNDLIZER_BUNDLE_OUTPUTPOINT_LABEL);
                    break;
                }

                case AssetGraphSettings.BUNDLIZER_RESOURCES_OUTPUTPOINT_LABEL: {
                    var labelPointV3 = new Vector3(centerPointV3.x - ((AssetGraphSettings.BUNDLIZER_RESOURCES_OUTPUTPOINT_LABEL.Length * 6f) / 2), centerPointV3.y - 24f, 0f);
                    Handles.Label(labelPointV3, AssetGraphSettings.BUNDLIZER_RESOURCES_OUTPUTPOINT_LABEL);
                    break;
                }

                default: {
                    var labelPointV3 = new Vector3(centerPointV3.x - ((label.Length * 7f) / 2), centerPointV3.y - 24f, 0f);
                    Handles.Label(labelPointV3, label);
                    break;
                }
                }
            }

            // draw connection arrow.
            if (Node.scaleFactor == Node.SCALE_MAX)
            {
                GUI.DrawTexture(
                    new Rect(
                        endV3.x - AssetGraphGUISettings.CONNECTION_ARROW_WIDTH + 4f,
                        endV3.y - (AssetGraphGUISettings.CONNECTION_ARROW_HEIGHT / 2f) - 1f,
                        AssetGraphGUISettings.CONNECTION_ARROW_WIDTH,
                        AssetGraphGUISettings.CONNECTION_ARROW_HEIGHT
                        ),
                    connectionArrowTex
                    );
            }

            /*
             *      draw throughtput badge.
             */
            var throughputCount = 0;

            foreach (var list in throughputListDict.Values)
            {
                throughputCount += list.Count;
            }
            var offsetSize = throughputCount.ToString().Length * 20f;

            buttonRect = new Rect(centerPointV3.x - offsetSize / 2f, centerPointV3.y - 7f, offsetSize, 20f);

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

            if (GUI.Button(buttonRect, throughputCount.ToString(), connectionButtonStyle))
            {
                conInsp.UpdateCon(this, throughputListDict);
                Emit(new OnConnectionEvent(OnConnectionEvent.EventType.EVENT_CONNECTION_TAPPED, this));
            }
        }
        private void OnEnable()
        {
            Color backColor             = GUI.backgroundColor;
            Color contentColor          = GUI.contentColor;
            float line                  = EditorGUIUtility.singleLineHeight;
            SerializedProperty property = serializedObject.FindProperty("services");

            _services = new ReorderableList(serializedObject, property);
            _services.showDefaultBackground = true;
            _services.elementHeight         = line + 6;

            _services.drawHeaderCallback = (rect) =>
            {
                EditorGUI.LabelField(rect, "Core Framework Services");
            };

            _services.drawElementCallback = (Rect rect, int index, bool active, bool focused) =>
            {
                float width = rect.width - 22;
                SerializedProperty element = _services.serializedProperty.GetArrayElementAtIndex(index);

                if (GUI.Button(new Rect(rect.x + rect.width - 20, rect.y + 4, 18, line), EditorGUIUtility.IconContent("_Popup").image, GUIStyle.none))
                {
                    GenericMenu menu = new GenericMenu();
                    menu.AddItem(new GUIContent("Edit"), false, delegate()
                    {
                        Selection.activeObject = element.objectReferenceValue;
                    });

                    menu.AddItem(new GUIContent("Remove"), false, delegate()
                    {
                        if (!_gameConfiguration.services[index])
                        {
                            _gameConfiguration.services.RemoveAt(index);
                            EditorUtility.SetDirty(_gameConfiguration);
                        }
                        else if (EditorUtility.DisplayDialog("Remove " + ObjectNames.NicifyVariableName(_gameConfiguration.services[index].name) + "?", "Are you sure you want to remove this service? This will delete the ScriptableObject and can't be undone.", "Yes", "No"))
                        {
                            AssetDatabase.DeleteAsset(AssetDatabase.GetAssetOrScenePath(element.objectReferenceValue));
                            _gameConfiguration.services.RemoveAt(index);
                            EditorUtility.SetDirty(_gameConfiguration);
                        }
                    });

                    menu.ShowAsContext();
                }

                EditorGUI.PropertyField(new Rect(rect.x, rect.y + 2, width, line), element, GUIContent.none);
            };

            _services.onAddCallback = (list) =>
            {
                Type[]      allServiceTypes = GetAllServiceTypes();
                GenericMenu servicesMenu    = new GenericMenu();
                foreach (var serviceType in allServiceTypes)
                {
                    servicesMenu.AddItem(new GUIContent(ObjectNames.NicifyVariableName(serviceType.Name)), false, delegate(object service)
                    {
                        Type styp = service as Type;
                        foreach (var assy in AppDomain.CurrentDomain.GetAssemblies())
                        {
                            foreach (var typ in assy.GetTypes())
                            {
                                if (typ.Name == styp.Name + "Config" || typ.Name == styp.Name + "Configuration")
                                {
                                    serializedObject.ApplyModifiedProperties();
                                    object so = ScriptableObject.CreateInstance(typ);
                                    if (so == null || (so as ServiceConfiguration) == null)
                                    {
                                        return;
                                    }
                                    serializedObject.ApplyModifiedProperties();
                                    string path = AssetDatabase.GetAssetOrScenePath(serializedObject.targetObject);
                                    path        = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + styp.Name + ".asset";
                                    AssetDatabase.CreateAsset(so as ServiceConfiguration, path);
                                    if (so != null)
                                    {
                                        _gameConfiguration.services.Add(so as ServiceConfiguration);
                                        EditorUtility.SetDirty(_gameConfiguration);
                                    }
                                    return;
                                }
                            }
                        }
                    }, serviceType);
                }
                servicesMenu.ShowAsContext();
            };
        }
 void DrawContextMenu()
 {
     GenericMenu menu = new GenericMenu();
     foreach(StateMenuItem it in menuItems) {
         menu.AddItem(new GUIContent("Add State/" + it.name), false, AddStateToMachine, it);
     }
     menu.AddItem(new GUIContent("Add State/Sub Machine"), false, AddSubMachine);
     menu.AddItem(new GUIContent("Add Trigger"), false, AddTrigger);
     menu.ShowAsContext ();
 }
Beispiel #39
0
        void OnGeneralUI(Rect rect)
        {
            var e = Event.current;

            // Selection
            if (e.type == EventType.mouseDown)
            {
                GUI.FocusControl(null);
                m_SelectedCurve         = null;
                m_SelectedKeyframeIndex = -1;
                bool used = false;

                var   hit            = CanvasToCurve(e.mousePosition);
                float curvePickValue = CurveToCanvas(hit).y;

                // Try and select a curve
                foreach (var curve in m_Curves)
                {
                    if (!curve.Value.editable || !curve.Value.visible)
                    {
                        continue;
                    }

                    var   prop      = curve.Key;
                    var   state     = curve.Value;
                    var   animCurve = prop.animationCurveValue;
                    float hitY      = animCurve.length == 0
                        ? state.zeroKeyConstantValue
                        : animCurve.Evaluate(hit.x);

                    var curvePos = CurveToCanvas(new Vector3(hit.x, hitY));

                    if (Mathf.Abs(curvePos.y - curvePickValue) < settings.curvePickingDistance)
                    {
                        m_SelectedCurve = prop;

                        if (e.clickCount == 2 && e.button == 0)
                        {
                            // Create a keyframe on double-click on this curve
                            EditCreateKeyframe(animCurve, hit, true, state.zeroKeyConstantValue);
                            SaveCurve(prop, animCurve);
                        }
                        else if (e.button == 1)
                        {
                            // Curve context menu
                            var menu = new GenericMenu();
                            menu.AddItem(new GUIContent("Add Key"), false, (x) =>
                            {
                                var action     = (MenuAction)x;
                                var curveValue = action.curve.animationCurveValue;
                                action.curve.serializedObject.Update();
                                EditCreateKeyframe(curveValue, hit, true, 0f);
                                SaveCurve(action.curve, curveValue);
                                action.curve.serializedObject.ApplyModifiedProperties();
                            }, new MenuAction(prop, hit));
                            menu.ShowAsContext();
                            e.Use();
                            used = true;
                        }
                    }
                }

                if (e.clickCount == 2 && e.button == 0 && m_SelectedCurve == null)
                {
                    // Create a keyframe on every curve on double-click
                    foreach (var curve in m_Curves)
                    {
                        if (!curve.Value.editable || !curve.Value.visible)
                        {
                            continue;
                        }

                        var prop      = curve.Key;
                        var state     = curve.Value;
                        var animCurve = prop.animationCurveValue;
                        EditCreateKeyframe(animCurve, hit, e.alt, state.zeroKeyConstantValue);
                        SaveCurve(prop, animCurve);
                    }
                }
                else if (!used && e.button == 1)
                {
                    // Global context menu
                    var menu = new GenericMenu();
                    menu.AddItem(new GUIContent("Add Key At Position"), false, () => ContextMenuAddKey(hit, false));
                    menu.AddItem(new GUIContent("Add Key On Curves"), false, () => ContextMenuAddKey(hit, true));
                    menu.ShowAsContext();
                }

                e.Use();
            }

            // Delete selected key(s)
            if (e.type == EventType.keyDown && (e.keyCode == KeyCode.Delete || e.keyCode == KeyCode.Backspace))
            {
                if (m_SelectedKeyframeIndex != -1 && m_SelectedCurve != null)
                {
                    var animCurve = m_SelectedCurve.animationCurveValue;
                    var length    = animCurve.length;

                    if (m_Curves[m_SelectedCurve].minPointCount < length && length >= 0)
                    {
                        EditDeleteKeyframe(animCurve, m_SelectedKeyframeIndex);
                        m_SelectedKeyframeIndex = -1;
                        SaveCurve(m_SelectedCurve, animCurve);
                    }

                    e.Use();
                }
            }
        }
    void DrawTriggerInspector(int windowID)
    {
        TriggerManager[] tempKeys = new TriggerManager[triggerInspectorPositions.Count];
        triggerInspectorPositions.Keys.CopyTo(tempKeys, 0);
        TriggerManager curTrigger = tempKeys[windowID - stateInspectorPositions.Count];

        if(Event.current.type == EventType.MouseDown && Event.current.button == 1) {
            GenericMenu menu = new GenericMenu();
            menu.AddItem(new GUIContent("Delete"), false, DeleteTrigger, curTrigger);
            menu.ShowAsContext ();
            Event.current.Use();
        }

        GUILayout.Label("From --> Obs --> To");
        GUILayout.BeginHorizontal();
        curTrigger.owner = LineStateSelector(curTrigger.owner, Color.cyan, windowID, curTrigger.inspectorCorner, null, Direction.Backwards);
        GUILayout.FlexibleSpace();
        curTrigger.watched = LineStateSelector((State)curTrigger.watched, Color.green, windowID, curTrigger.inspectorCorner, null, Direction.None);
        GUILayout.FlexibleSpace();
        curTrigger.target = LineStateSelector(curTrigger.target, Color.blue, windowID, curTrigger.inspectorCorner, null, Direction.Forwards);
        GUILayout.EndHorizontal();
        if(curTrigger.watched != null && curTrigger.watched.GetExposedVariables().Length > 0)
        {
            curTrigger.observedIndex = curTrigger.watched.DrawObservableSelector(curTrigger.observedIndex);
            GUI.contentColor = Color.black;
            EditorGUIUtility.LookLikeControls();

            curTrigger.mode = (TriggerMode)EditorGUILayout.EnumPopup(curTrigger.mode);
            switch(curTrigger.obsType) {
            case ObservedType.integer:
                curTrigger.intTarget = EditorGUILayout.IntField(curTrigger.intTarget, GUILayout.MaxWidth(triggerInspectorPositions[curTrigger].width));
                break;
            case ObservedType.floatingPoint:
                curTrigger.floatTarget = EditorGUILayout.FloatField(curTrigger.floatTarget, GUILayout.MaxWidth(triggerInspectorPositions[curTrigger].width));
                break;
            case ObservedType.boolean:
                curTrigger.boolTarget = EditorGUILayout.Toggle(curTrigger.boolTarget, GUILayout.MaxWidth(triggerInspectorPositions[curTrigger].width));
                break;
            }
            GUI.contentColor = Color.white;
            EditorGUIUtility.LookLikeInspector();
        }
        if(curTrigger.watched == null) {
            GUILayout.Label("Observing Memory");
            EditorGUIUtility.LookLikeControls();
            curTrigger.memoryKey = EditorGUILayout.TextField(curTrigger.memoryKey);
            curTrigger.mode = (TriggerMode)EditorGUILayout.EnumPopup(curTrigger.mode);
            curTrigger.floatTarget = EditorGUILayout.FloatField(curTrigger.floatTarget, GUILayout.MaxWidth(triggerInspectorPositions[curTrigger].width));
            EditorGUIUtility.LookLikeInspector();
        }
        GUI.DragWindow();
        curTrigger.inspectorCorner = new Vector2(triggerInspectorPositions[curTrigger].x, triggerInspectorPositions[curTrigger].y);
    }
        protected override void OnInspectorDefaultGUI()
        {
            base.OnInspectorDefaultGUI();

            GUILayout.BeginHorizontal();
            GUI.enabled = !EditorApplication.isPlaying && Target.DefaultProcedure != "";
            GUILayout.Label("Default: " + Target.DefaultProcedure);
            GUI.enabled = !EditorApplication.isPlaying;
            GUILayout.FlexibleSpace();
            GUI.enabled = !EditorApplication.isPlaying && Target.ActivatedProcedures.Count > 0;
            if (GUILayout.Button("Set Default", EditorGlobalTools.Styles.MiniPopup))
            {
                GenericMenu gm = new GenericMenu();
                for (int i = 0; i < Target.ActivatedProcedures.Count; i++)
                {
                    int j = i;
                    gm.AddItem(new GUIContent(Target.ActivatedProcedures[j]), Target.DefaultProcedure == Target.ActivatedProcedures[j], () =>
                    {
                        Undo.RecordObject(target, "Set Default Procedure");
                        Target.DefaultProcedure = Target.ActivatedProcedures[j];
                        HasChanged();
                    });
                }
                gm.ShowAsContext();
            }
            GUI.enabled = !EditorApplication.isPlaying;
            GUILayout.EndHorizontal();

            GUILayout.BeginVertical(EditorGlobalTools.Styles.Box);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Enabled Procedures:");
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            for (int i = 0; i < Target.ActivatedProcedures.Count; i++)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label((i + 1) + "." + Target.ActivatedProcedures[i]);
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("▲", EditorStyles.miniButtonLeft))
                {
                    if (i > 0)
                    {
                        Undo.RecordObject(target, "Set Procedure Order");
                        string procedure = Target.ActivatedProcedures[i];
                        Target.ActivatedProcedures.RemoveAt(i);
                        Target.ActivatedProcedures.Insert(i - 1, procedure);
                        HasChanged();
                        continue;
                    }
                }
                if (GUILayout.Button("▼", EditorStyles.miniButtonMid))
                {
                    if (i < Target.ActivatedProcedures.Count - 1)
                    {
                        Undo.RecordObject(target, "Set Procedure Order");
                        string procedure = Target.ActivatedProcedures[i];
                        Target.ActivatedProcedures.RemoveAt(i);
                        Target.ActivatedProcedures.Insert(i + 1, procedure);
                        HasChanged();
                        continue;
                    }
                }
                if (GUILayout.Button("Edit", EditorStyles.miniButtonMid))
                {
                    MonoScriptToolkit.OpenMonoScript(Target.ActivatedProcedures[i]);
                }
                if (GUILayout.Button("Delete", EditorStyles.miniButtonRight))
                {
                    Undo.RecordObject(target, "Delete Procedure");

                    if (Target.DefaultProcedure == Target.ActivatedProcedures[i])
                    {
                        Target.DefaultProcedure = "";
                    }

                    Target.ActivatedProcedures.RemoveAt(i);

                    if (Target.DefaultProcedure == "" && Target.ActivatedProcedures.Count > 0)
                    {
                        Target.DefaultProcedure = Target.ActivatedProcedures[0];
                    }

                    HasChanged();
                }
                GUILayout.EndHorizontal();
            }

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Add Procedure", EditorGlobalTools.Styles.MiniPopup))
            {
                GenericMenu gm    = new GenericMenu();
                List <Type> types = ReflectionToolkit.GetTypesInRunTimeAssemblies(type =>
                {
                    return(type.IsSubclassOf(typeof(ProcedureBase)) && !type.IsAbstract);
                });
                for (int i = 0; i < types.Count; i++)
                {
                    int j = i;
                    if (Target.ActivatedProcedures.Contains(types[j].FullName))
                    {
                        gm.AddDisabledItem(new GUIContent(types[j].FullName));
                    }
                    else
                    {
                        gm.AddItem(new GUIContent(types[j].FullName), false, () =>
                        {
                            Undo.RecordObject(target, "Add Procedure");

                            Target.ActivatedProcedures.Add(types[j].FullName);
                            if (Target.DefaultProcedure == "")
                            {
                                Target.DefaultProcedure = Target.ActivatedProcedures[0];
                            }

                            HasChanged();
                        });
                    }
                }
                gm.ShowAsContext();
            }
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();

            GUI.enabled = true;
        }
        private void OnEnable()
        {
            Action <ReorderableList, SerializedProperty> fnAssetDropDown = delegate(ReorderableList list, SerializedProperty property)
            {
                var existingAttribute = new List <string>();
                for (int i = 0; i < property.arraySize; ++i)
                {
                    existingAttribute.Add(property.GetArrayElementAtIndex(i).FindPropertyRelative("attribute.m_Name").stringValue);
                }

                var menu = new GenericMenu();
                foreach (var attributeName in VFXAttribute.AllIncludingVariadicReadWritable.Except(existingAttribute).OrderBy(o => o))
                {
                    var attribute = VFXAttribute.Find(attributeName);
                    menu.AddItem(new GUIContent(attribute.name), false, () =>
                    {
                        serializedObject.Update();
                        property.arraySize++;

                        var newElement = property.GetArrayElementAtIndex(property.arraySize - 1);
                        newElement.FindPropertyRelative("attribute.m_Name").stringValue = attribute.name;
                        newElement.FindPropertyRelative("type").intValue = (int)attribute.type;

                        var size         = VFXExpression.TypeToSize(attribute.type);
                        var values       = newElement.FindPropertyRelative("values");
                        values.arraySize = size;

                        var initialValues = new float[size];
                        if (attribute.type == VFXValueType.Float)
                        {
                            initialValues[0] = attribute.value.Get <float>();
                        }
                        else if (attribute.type == VFXValueType.Float2)
                        {
                            var v            = attribute.value.Get <Vector2>();
                            initialValues[0] = v.x;
                            initialValues[1] = v.y;
                        }
                        else if (attribute.type == VFXValueType.Float3)
                        {
                            var v            = attribute.value.Get <Vector3>();
                            initialValues[0] = v.x;
                            initialValues[1] = v.y;
                            initialValues[2] = v.z;
                        }
                        else if (attribute.type == VFXValueType.Float4)
                        {
                            var v            = attribute.value.Get <Vector4>();
                            initialValues[0] = v.x;
                            initialValues[1] = v.y;
                            initialValues[2] = v.z;
                            initialValues[3] = v.w;
                        }
                        else if (attribute.type == VFXValueType.Int32)
                        {
                            initialValues[0] = attribute.value.Get <int>();
                        }
                        else if (attribute.type == VFXValueType.Uint32)
                        {
                            initialValues[0] = attribute.value.Get <uint>();
                        }
                        else if (attribute.type == VFXValueType.Boolean)
                        {
                            initialValues[0] = attribute.value.Get <bool>() ? 1.0f : 0.0f;
                        }
                        for (int i = 0; i < size; ++i)
                        {
                            values.GetArrayElementAtIndex(i).floatValue = initialValues[i];
                        }
                        serializedObject.ApplyModifiedProperties();
                    });
                }
                menu.ShowAsContext();
            };

            Action <Rect, SerializedProperty, int> fnDrawElement = delegate(Rect r, SerializedProperty property, int index)
            {
                var element = property.GetArrayElementAtIndex(index);

                var label      = element.FindPropertyRelative("attribute.m_Name").stringValue;
                var labelWidth = 110;//GUI.skin.label.CalcSize(new GUIContent(label)); //Should be maximized among all existing property, for now, angularVelocity is considered as maximum

                EditorGUI.LabelField(new Rect(r.x, r.y, labelWidth, EditorGUIUtility.singleLineHeight), label);
                var valueType       = (VFXValueType)element.FindPropertyRelative("type").intValue;
                var valueSize       = VFXExpression.TypeToSize(valueType);
                var fieldWidth      = (r.width - labelWidth) / valueSize;
                var emptyGUIContent = new GUIContent(string.Empty);
                var valuesProperty  = element.FindPropertyRelative("values");
                if (valueType == VFXValueType.Float ||
                    valueType == VFXValueType.Float2 ||
                    valueType == VFXValueType.Float3 ||
                    valueType == VFXValueType.Float4)
                {
                    if (label.Contains("color") && valueType == VFXValueType.Float3)
                    {
                        var oldColor = new Color(valuesProperty.GetArrayElementAtIndex(0).floatValue,
                                                 valuesProperty.GetArrayElementAtIndex(1).floatValue,
                                                 valuesProperty.GetArrayElementAtIndex(2).floatValue);

                        EditorGUI.BeginChangeCheck();
                        var newColor = EditorGUI.ColorField(new Rect(r.x + labelWidth, r.y, fieldWidth * 3, EditorGUIUtility.singleLineHeight), oldColor);
                        if (EditorGUI.EndChangeCheck())
                        {
                            valuesProperty.GetArrayElementAtIndex(0).floatValue = newColor.r;
                            valuesProperty.GetArrayElementAtIndex(1).floatValue = newColor.g;
                            valuesProperty.GetArrayElementAtIndex(2).floatValue = newColor.b;
                        }
                    }
                    else
                    {
                        for (int i = 0; i < valueSize; ++i)
                        {
                            EditorGUI.PropertyField(new Rect(r.x + labelWidth + fieldWidth * i, r.y, fieldWidth, EditorGUIUtility.singleLineHeight), valuesProperty.GetArrayElementAtIndex(i), emptyGUIContent);
                        }
                    }
                }
                else if (valueType == VFXValueType.Int32 ||
                         valueType == VFXValueType.Uint32 ||
                         valueType == VFXValueType.Boolean)
                {
                    var   oldValue = valuesProperty.GetArrayElementAtIndex(0).floatValue;
                    float newValue;
                    var   currentRect = new Rect(r.x + labelWidth, r.y, fieldWidth, EditorGUIUtility.singleLineHeight);
                    EditorGUI.BeginChangeCheck();
                    if (valueType == VFXValueType.Boolean)
                    {
                        newValue = EditorGUI.Toggle(currentRect, emptyGUIContent, oldValue != 0.0f) ? 1.0f : 0.0f;
                    }
                    else
                    {
                        newValue = (float)EditorGUI.LongField(currentRect, emptyGUIContent, (long)oldValue);
                        newValue = newValue < 0.0f ? 0.0f : newValue;
                    }
                    if (EditorGUI.EndChangeCheck())
                    {
                        valuesProperty.GetArrayElementAtIndex(0).floatValue = newValue;
                        serializedObject.ApplyModifiedProperties();
                    }
                }
            };

            onClipEnterProperty = serializedObject.FindProperty("activationBehavior.onClipEnter.m_Name");
            onClipExitProperty  = serializedObject.FindProperty("activationBehavior.onClipExit.m_Name");

            var clipEnterAttributesProperty = serializedObject.FindProperty("activationBehavior.clipEnterEventAttributes");
            var clipExitAttributesProperty  = serializedObject.FindProperty("activationBehavior.clipExitEventAttributes");

            clipEnterAttributesPropertyList = new ReorderableList(serializedObject, clipEnterAttributesProperty, true, true, true, true);
            clipExitAttributesPropertyList  = new ReorderableList(serializedObject, clipExitAttributesProperty, true, true, true, true);

            clipEnterAttributesPropertyList.drawHeaderCallback = (Rect r) => { EditorGUI.LabelField(r, "Enter Event Attributes"); };
            clipExitAttributesPropertyList.drawHeaderCallback  = (Rect r) => { EditorGUI.LabelField(r, "Exit Event Attributes"); };

            clipEnterAttributesPropertyList.onAddDropdownCallback += (Rect buttonRect, ReorderableList list) => fnAssetDropDown(list, clipEnterAttributesProperty);
            clipExitAttributesPropertyList.onAddDropdownCallback  += (Rect buttonRect, ReorderableList list) => fnAssetDropDown(list, clipExitAttributesProperty);

            clipEnterAttributesPropertyList.drawElementCallback = (Rect r, int index, bool active, bool focused) => fnDrawElement(r, clipEnterAttributesProperty, index);
            clipExitAttributesPropertyList.drawElementCallback  = (Rect r, int index, bool active, bool focused) => fnDrawElement(r, clipExitAttributesProperty, index);
        }
    void DrawStateInspector(int windowID)
    {
        State[] tempKeys = new State[stateInspectorPositions.Count];
        stateInspectorPositions.Keys.CopyTo(tempKeys, 0);
        State curState = tempKeys[windowID];

        if(Event.current.type == EventType.MouseDown && Event.current.button == 1) {
            GenericMenu menu = new GenericMenu();
            menu.AddItem(new GUIContent("Delete"), false, DeleteState, curState);
            menu.ShowAsContext ();
            Event.current.Use();
        }

        foreach(LinkedStateReference stRef in curState.GetStateTransitions()) {
            GUILayout.BeginHorizontal();
            GUILayout.Label(stRef.GetLabel());

            stRef.SetState(LineStateSelector (stRef.GetState(), Color.blue, windowID, curState.inspectorCorner, curState, Direction.Forwards));

            GUILayout.EndHorizontal();
        }

        if(curState.GetType() == typeof(Machine)) {
            if(GUILayout.Button("Push"))
            {
                Selection.activeGameObject = curState.gameObject;
                stMachine = (Machine)curState;
                stateInspectorPositions = new Dictionary<State, Rect>();
                triggerInspectorPositions = new Dictionary<TriggerManager, Rect>();
                return;
            }
        }

        curState.DrawInspector();

        GUI.DragWindow();
        curState.inspectorCorner = new Vector2(stateInspectorPositions[curState].x, stateInspectorPositions[curState].y);
    }
Beispiel #44
0
    private void ShowUI()
    {
        GUI.enabled = true;

        #region Classify
        EditorGUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        if (GUILayout.Button("Model", "ButtonLeft", GUILayout.Width(80)))
        {
            _currentClassify = "Model";
        }
        if (GUILayout.Button("Rig", "ButtonMid", GUILayout.Width(80)))
        {
            _currentClassify = "Rig";
        }
        if (GUILayout.Button("Animations", "ButtonRight", GUILayout.Width(80)))
        {
            _currentClassify = "Animations";
        }
        GUILayout.FlexibleSpace();
        EditorGUILayout.EndHorizontal();
        #endregion

        if (_currentClassify == "Model")
        {
            #region STL Meshes
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("STL Meshes", "BoldLabel");
            GUILayout.Label("(File Type:Binary)", "BoldLabel");
            EditorGUILayout.EndHorizontal();

            GUI.enabled = false;
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Scale Factor", GUILayout.Width(120));
            GUILayout.TextField("1");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("File Scale", GUILayout.Width(120));
            GUILayout.TextField("1");
            EditorGUILayout.EndHorizontal();

            if (_fileName == "" && _trianglescount == "")
            {
                GetFileNameAndTrianglesCount();
            }

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("File Name", GUILayout.Width(120));
            _fileName = GUILayout.TextField(_fileName);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Triangles Count", GUILayout.Width(120));
            _trianglescount = GUILayout.TextField(_trianglescount);
            EditorGUILayout.EndHorizontal();
            GUI.enabled = true;

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Mesh Compression", GUILayout.Width(120));
            if (GUILayout.Button(_meshCompression, "MiniPopup"))
            {
                GenericMenu gm = new GenericMenu();
                gm.AddItem(new GUIContent("Off"), "Off" == _meshCompression, delegate() { _meshCompression = "Off"; });
                gm.AddItem(new GUIContent("On"), "On" == _meshCompression, delegate() { _meshCompression = "On"; });
                gm.ShowAsContext();
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Single Triangles Number", GUILayout.Width(120));
            _singleTrianglesNumber = EditorGUILayout.IntField(_singleTrianglesNumber);
            EditorGUILayout.EndHorizontal();

            GUI.enabled = false;
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Read/Write Enabled", GUILayout.Width(120));
            GUILayout.Toggle(true, "");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Optimize Mesh", GUILayout.Width(120));
            GUILayout.Toggle(false, "");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Import BlendShapes", GUILayout.Width(120));
            GUILayout.Toggle(false, "");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Generate Colliders", GUILayout.Width(120));
            GUILayout.Toggle(false, "");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Keep Quads", GUILayout.Width(120));
            GUILayout.Toggle(false, "");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Swap UVs", GUILayout.Width(120));
            GUILayout.Toggle(false, "");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Generate Lightmap UVs", GUILayout.Width(120));
            GUILayout.Toggle(false, "");
            EditorGUILayout.EndHorizontal();
            GUI.enabled = true;
            #endregion

            #region Normals & Tangents
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Normals & Tangents", "BoldLabel");
            EditorGUILayout.EndHorizontal();

            GUI.enabled = false;
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Normals", GUILayout.Width(120));
            GUILayout.Button("None", "MiniPopup");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Smoothing Angle", GUILayout.Width(120));
            GUILayout.HorizontalSlider(0.3f, 0, 1);
            GUILayout.TextField("60");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Tangents", GUILayout.Width(120));
            GUILayout.Button("None - (Normals required)", "MiniPopup");
            EditorGUILayout.EndHorizontal();
            GUI.enabled = true;
            #endregion

            #region Materials
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Materials", "BoldLabel");
            EditorGUILayout.EndHorizontal();

            GUI.enabled = false;
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Import Materials", GUILayout.Width(120));
            GUILayout.Toggle(false, "");
            EditorGUILayout.EndHorizontal();
            GUI.enabled = true;
            #endregion
        }
        else if (_currentClassify == "Rig")
        {
            #region Rig
            GUI.enabled = false;
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Animation Type", GUILayout.Width(120));
            GUILayout.Button("Legacy", "MiniPopup");
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Generation", GUILayout.Width(120));
            GUILayout.Button("Don't Import", "MiniPopup");
            EditorGUILayout.EndHorizontal();
            GUI.enabled = true;
            #endregion
        }
        else if (_currentClassify == "Animations")
        {
            #region Animations
            GUI.enabled = false;
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Import Animation", GUILayout.Width(120));
            GUILayout.Toggle(false, "");
            EditorGUILayout.EndHorizontal();
            GUI.enabled = true;

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.HelpBox("No animation data available in this STL model.", MessageType.Info);
            EditorGUILayout.EndHorizontal();
            #endregion
        }

        #region Apply
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("");
        EditorGUILayout.EndHorizontal();

        GUI.enabled = false;
        EditorGUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        GUILayout.Button("Revert");
        GUILayout.Button("Apply");
        EditorGUILayout.EndHorizontal();
        GUI.enabled = true;
        #endregion

        #region CreateInstance
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("");
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        if (GUILayout.Button("CreateInstance", GUILayout.Width(160)))
        {
            CreateInstance();
        }
        _isSaveMesh = GUILayout.Toggle(_isSaveMesh, "Save Mesh");
        GUILayout.FlexibleSpace();
        EditorGUILayout.EndHorizontal();
        #endregion
    }
        void DoContextMenu()
        {
            var menu = new GenericMenu();

            menu.AddItem(new GUIContent("Reset All"), false, () =>
            {
                if (!UnityEditor.EditorUtility.DisplayDialog("Reset All Settings", "Reset all settings? This is not undo-able.", "Reset", "Cancel"))
                {
                    return;
                }

                // Do not reset SettingVisibility.Unregistered
                foreach (var pref in UserSettings.FindUserSettings(m_Assemblies, SettingVisibility.Visible | SettingVisibility.Hidden | SettingVisibility.Unlisted))
                {
                    pref.Reset();
                }

                m_SettingsInstance.Save();
            });

            if (EditorPrefs.GetBool("DeveloperMode", false))
            {
                menu.AddSeparator("");

                menu.AddItem(new GUIContent("Developer/List Settings By Key"), listByKey, () =>
                {
                    listByKey.SetValue(!listByKey, true);
                    SearchForUserSettingAttributes();
                });

                menu.AddSeparator("Developer/");

                menu.AddItem(new GUIContent("Developer/Show User Settings"), showUserSettings, () =>
                {
                    showUserSettings.SetValue(!showUserSettings, true);
                    SearchForUserSettingAttributes();
                });

                menu.AddItem(new GUIContent("Developer/Show Project Settings"), showProjectSettings, () =>
                {
                    showProjectSettings.SetValue(!showProjectSettings, true);
                    SearchForUserSettingAttributes();
                });

                menu.AddSeparator("Developer/");

                menu.AddItem(new GUIContent("Developer/Show Unlisted Settings"), showHiddenSettings, () =>
                {
                    showHiddenSettings.SetValue(!showHiddenSettings, true);
                    SearchForUserSettingAttributes();
                });

                menu.AddItem(new GUIContent("Developer/Show Unregistered Settings"), showUnregisteredSettings, () =>
                {
                    showUnregisteredSettings.SetValue(!showUnregisteredSettings, true);
                    SearchForUserSettingAttributes();
                });

                menu.AddSeparator("Developer/");

                menu.AddItem(new GUIContent("Developer/Open Project Settings File"), false, () =>
                {
                    var project = m_SettingsInstance.GetRepository(SettingsScope.Project);

                    if (project != null)
                    {
                        var path = Path.GetFullPath(project.path);
                        System.Diagnostics.Process.Start(path);
                    }
                });

                menu.AddItem(new GUIContent("Developer/Print All Settings"), false, () =>
                {
                    Debug.Log(UserSettings.GetSettingsString(m_Assemblies));
                });

#if UNITY_2019_1_OR_NEWER
                menu.AddSeparator("Developer/");
                menu.AddItem(new GUIContent("Developer/Recompile Scripts"), false, UnityEditorInternal.InternalEditorUtility.RequestScriptReload);
#endif
            }

            menu.ShowAsContext();
        }
Beispiel #46
0
        private bool HistoryEntry(GitLogEntry entry, LogEntryState state, bool selected)
        {
            var entryRect       = GUILayoutUtility.GetRect(Styles.HistoryEntryHeight, Styles.HistoryEntryHeight);
            var timelineBarRect = new Rect(entryRect.x + Styles.BaseSpacing, 0, 2, Styles.HistoryDetailsHeight);

            if (Event.current.type == EventType.Repaint)
            {
                var keyboardFocus = GUIUtility.keyboardControl == listID;

                var summaryRect   = new Rect(entryRect.x, entryRect.y + (Styles.BaseSpacing / 2), entryRect.width, Styles.HistorySummaryHeight + Styles.BaseSpacing);
                var timestampRect = new Rect(entryRect.x, entryRect.yMax - Styles.HistoryDetailsHeight - (Styles.BaseSpacing / 2), entryRect.width, Styles.HistoryDetailsHeight);
                var authorRect    = new Rect(timestampRect.xMax, timestampRect.y, timestampRect.width, timestampRect.height);

                var contentOffset = new Vector2(Styles.BaseSpacing * 2, 0);

                Styles.Label.Draw(entryRect, "", false, false, selected, keyboardFocus);

                Styles.Label.contentOffset = contentOffset;
                Styles.HistoryEntryDetailsStyle.contentOffset = contentOffset;

                Styles.Label.Draw(summaryRect, entry.Summary, false, false, selected, keyboardFocus);
                Styles.HistoryEntryDetailsStyle.Draw(timestampRect, entry.PrettyTimeString + "     " + entry.AuthorName, false, false, selected, keyboardFocus);

                if (!string.IsNullOrEmpty(entry.MergeA))
                {
                    const float MergeIndicatorWidth  = 10.28f;
                    const float MergeIndicatorHeight = 12f;
                    var         mergeIndicatorRect   = new Rect(entryRect.x + 7, summaryRect.y, MergeIndicatorWidth, MergeIndicatorHeight);

                    GUI.DrawTexture(mergeIndicatorRect, Styles.MergeIcon);

                    DrawTimelineRectAroundIconRect(entryRect, mergeIndicatorRect);

                    summaryRect.Set(mergeIndicatorRect.xMax, summaryRect.y, summaryRect.width - MergeIndicatorWidth, summaryRect.height);
                }

                if (state == LogEntryState.Local && string.IsNullOrEmpty(entry.MergeA))
                {
                    const float LocalIndicatorSize = 6f;
                    var         localIndicatorRect = new Rect(entryRect.x + (Styles.BaseSpacing - 2), summaryRect.y + 5, LocalIndicatorSize, LocalIndicatorSize);

                    DrawTimelineRectAroundIconRect(entryRect, localIndicatorRect);

                    GUI.DrawTexture(localIndicatorRect, Styles.LocalCommitIcon);

                    summaryRect.Set(localIndicatorRect.xMax, summaryRect.y, summaryRect.width - LocalIndicatorSize, summaryRect.height);
                }

                if (state == LogEntryState.Normal && string.IsNullOrEmpty(entry.MergeA))
                {
                    const float NormalIndicatorWidth  = 6f;
                    const float NormalIndicatorHeight = 6f;

                    Rect normalIndicatorRect = new Rect(entryRect.x + (Styles.BaseSpacing - 2),
                                                        summaryRect.y + 5,
                                                        NormalIndicatorWidth,
                                                        NormalIndicatorHeight);

                    DrawTimelineRectAroundIconRect(entryRect, normalIndicatorRect);

                    GUI.DrawTexture(normalIndicatorRect, Styles.DotIcon);
                }
            }
            else if (Event.current.type == EventType.ContextClick && entryRect.Contains(Event.current.mousePosition))
            {
                GenericMenu menu = new GenericMenu();
                menu.AddItem(new GUIContent("Revert"), false, RevertCommit);
                menu.ShowAsContext();

                Event.current.Use();
            }
            else if (Event.current.type == EventType.MouseDown && entryRect.Contains(Event.current.mousePosition))
            {
                Event.current.Use();
                return(true);
            }

            return(false);
        }
Beispiel #47
0
	void Selector(SerializedProperty property) {

		SpineAnimation attrib = (SpineAnimation)attribute;

		GenericMenu menu = new GenericMenu();

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

		menu.ShowAsContext();
	}
    // This function is called every editor gui update. In here we are diong our magic to show all to the user in a nice way.
    public override void OnInspectorGUI()
    {
        //Setting styles
        if (_descBoxStyle == null)
        {
            _descBoxStyle                  = new GUIStyle(GUI.skin.FindStyle("Box"));
            _descBoxStyle.alignment        = TextAnchor.UpperLeft;
            _descBoxStyle.normal.textColor = Color.white;
            _descBoxStyle.stretchWidth     = true;

            _bigBoxStyle                   = new GUIStyle(GUI.skin.FindStyle("Box"));
            _bigBoxStyle.alignment         = TextAnchor.UpperLeft;
            _bigBoxStyle.normal.textColor  = Color.white;
            _bigBoxStyle.stretchHeight     = true;
            _bigBoxStyle.normal.background = (Texture2D)Resources.Load("SourceBack");

            _popupStyle               = new GUIStyle(GUI.skin.FindStyle("Popup"));
            _popupStyle.fontStyle     = (FontStyle.Normal);
            _popupStyle.stretchHeight = true;
        }

        EditorGUIUtility.LookLikeInspector();

        serializedObject.Update(); // update the serialized object since the last time this method was called.

        BaseAction myTarget = (BaseAction)target;

        myTarget.UpdateInspector();

        SerializedProperty script = serializedObject.FindProperty("m_Script");

        EditorGUILayout.PropertyField(script, new GUIContent("Script", myTarget.GetActionDescription()));


        //Show first public visible fields with the Attribute "ShowAtfirst"
        SerializedProperty prop = serializedObject.GetIterator();

        prop.NextVisible(true);
        do
        {
            if (ShouldShowFirst(prop))
            {
                EditorGUILayout.PropertyField(prop, true);
            }
        } while (prop.NextVisible(false));

        //then show Triggers


        Rect rect = EditorGUILayout.BeginVertical();

        GUI.Box(rect, "", _bigBoxStyle);

        if (myTarget.IsSupportCustomTriggers())
        {
            GUILayout.Space(5);

            // Add Trigger row - Combo-box + Add Button
            Rect addTriggerRect = EditorGUILayout.BeginHorizontal();
            {
                if (_triggerToAdd != null)
                {
                    // If user pressed on "Add" button -  add the selected trigger to the action's supported triggers
                    _supportedTriggers.InsertArrayElementAtIndex(0);
                    _supportedTriggers.GetArrayElementAtIndex(0).objectReferenceValue = myTarget.AddHiddenComponent(_triggerToAdd);

                    ((Trigger)_supportedTriggers.GetArrayElementAtIndex(0).objectReferenceValue).CleanRules();

                    _triggerToAdd = null;
                }

                GUILayout.Box("Add Triger", _popupStyle);

                var evt = Event.current;
                if (evt.type == EventType.MouseDown)
                {
                    //Getting all Triggers
                    List <System.Type> possibleTriggers = myTarget.GetSupprtedTriggers();

                    var mousePos = evt.mousePosition;
                    if (addTriggerRect.Contains(mousePos))
                    {
                        // Now create the menu, add items and show it
                        var menu = new GenericMenu();
                        for (int i = 0; i < possibleTriggers.Count; i++)
                        {
                            string triggerFriendlyName = "";
                            if (!_friendlyNames.ContainsKey(possibleTriggers[i].FullName))
                            {
                                GameObject g           = new GameObject("temp");
                                Trigger    triggerTemp = (Trigger)g.AddComponent(possibleTriggers[i]);
                                _friendlyNames.Add(possibleTriggers[i].FullName, triggerTemp.FriendlyName);
                                DestroyImmediate(g);
                            }

                            triggerFriendlyName = _friendlyNames[possibleTriggers[i].FullName];


                            menu.AddItem(new GUIContent(triggerFriendlyName), false, AddTrigger, possibleTriggers[i]);
                        }

                        menu.ShowAsContext();
                        evt.Use();
                    }
                }
            }
            EditorGUILayout.EndHorizontal();
        }

        // go over all the Action's supported triggers and add them to the inspector.
        for (int i = 0; i < _supportedTriggers.arraySize; i++)
        {
            //Get Trigger and update rules
            Trigger trigger = (Trigger)_supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue;
            if (trigger == null)
            {
                ((BaseAction)target).InitializeSupportedTriggers();
                EditorGUILayout.EndVertical();
                return;
            }

            // Trigger Row - Foldout + Reset trigger button + Delete trigger
            Rect triggerRect = EditorGUILayout.BeginHorizontal();
            {
                trigger.FoldoutOpen = GUIUtils.Foldout(trigger.FoldoutOpen, trigger.FriendlyName);
                if (trigger.FoldoutOpen)
                {
                    List <System.Type> supprtedRules1 = trigger.GetSupportedRules();
                    Rect rectRuleAddButton            = EditorGUILayout.BeginHorizontal();

                    GUILayout.Box("Add", _popupStyle, GUILayout.Width(50));
                    EditorGUILayout.EndHorizontal();

                    GUILayout.FlexibleSpace();

                    var evt = Event.current;
                    if (evt.type == EventType.MouseDown)
                    {
                        var mousePos = evt.mousePosition;
                        if (rectRuleAddButton.Contains(mousePos))
                        {
                            // Now create the menu, add items and show it
                            var menu1 = new GenericMenu();
                            for (int ri = 0; ri < supprtedRules1.Count(); ri++)
                            {
                                string ruleFriendlyName = "";
                                if (!_friendlyNames.ContainsKey(supprtedRules1[ri].FullName))
                                {
                                    GameObject g        = new GameObject("temp");
                                    BaseRule   ruleTemp = (BaseRule)g.AddComponent(supprtedRules1[ri]);
                                    _friendlyNames.Add(supprtedRules1[ri].FullName, ruleTemp.FriendlyName);
                                    DestroyImmediate(g);
                                }

                                ruleFriendlyName = _friendlyNames[supprtedRules1[ri].FullName];

                                menu1.AddItem(new GUIContent(ruleFriendlyName), false, AddRule, supprtedRules1[ri]);
                            }

                            menu1.ShowAsContext();
                            evt.Use();

                            _triggerToAddRuleTo = trigger;
                        }
                    }
                }
            }
            EditorGUILayout.EndHorizontal();

            SetTriggersContextMenu(triggerRect, myTarget, trigger);

            // show trigger's rules if opened
            if (trigger.FoldoutOpen)
            {
                SerializedObject   obj   = new SerializedObject(_supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue);
                SerializedProperty rules = obj.FindProperty("Rules");

                if (true)
                {
                    // Add Trigger row - Combo-box + Add Button
                    EditorGUILayout.BeginHorizontal();
                    {
                        //Adding combo-box control to the inspector with the list of triggers.
                        if (_triggerToAddRuleTo == trigger && _ruleToAdd != null)
                        {
                            // If user pressed on "Add" button -  add the selected trigger to the action's supported triggers
                            rules.InsertArrayElementAtIndex(0);
                            rules.GetArrayElementAtIndex(0).objectReferenceValue = myTarget.AddHiddenComponent(_ruleToAdd);

                            // initialize rules
                            _ruleToAdd          = null;
                            _triggerToAddRuleTo = null;
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                    GUILayout.Space(5);
                }



                for (int j = 0; j < rules.arraySize; j++)
                {
                    BaseRule rule = (BaseRule)rules.GetArrayElementAtIndex(j).objectReferenceValue;
                    DrawRuleInspector(rule);

                    //Reset Rule
                    if (_ruleToReset != null && _ruleToReset == rule)
                    {
                        rule.ActionOwner = null;
                        rules.GetArrayElementAtIndex(j).objectReferenceValue = myTarget.AddHiddenComponent(_ruleToReset.GetType());
                        // Save folded state
                        ((BaseRule)rules.GetArrayElementAtIndex(j).objectReferenceValue).FoldoutOpen = rule.FoldoutOpen;

                        _ruleToReset = null;
                    }

                    //Remove Rule
                    if (_ruleToRemove != null && _ruleToRemove == rule)
                    {
                        // delete the trigger and reorganize the array
                        var r = rules.GetArrayElementAtIndex(j).objectReferenceValue;
                        rules.DeleteArrayElementAtIndex(j);
                        ((BaseRule)r).ActionOwner = null;
                        for (int k = j; k < rules.arraySize - 1; k++)
                        {
                            rules.MoveArrayElement(k + 1, k);
                        }
                        rules.arraySize--;
                        _ruleToRemove = null;
                    }
                }

                //Save changes to the rule
                obj.ApplyModifiedProperties();
            }

            // Reset Trigger
            if (_triggerToReset != null && _triggerToReset == trigger)
            {
                trigger.ActionOwner = null;
                foreach (BaseRule r in trigger.Rules)
                {
                    r.ActionOwner = null;
                }
                _supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue = myTarget.AddHiddenComponent(trigger.GetType());

                Trigger oldTrigger = trigger;
                trigger = (Trigger)_supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue;

                trigger.CleanRules();
                //trigger.SetDefaults(myTarget);
                myTarget.SetDefaultTriggerValues(i, trigger);

                // Save folded state
                trigger.FoldoutOpen = oldTrigger.FoldoutOpen;


                _triggerToReset = null;
                break;
            }

            // Remove Trigger
            if (_triggerToRemove != null && _triggerToRemove == trigger)
            {
                // delete the trigger and reorganize the array

                _supportedTriggers.DeleteArrayElementAtIndex(i);
                trigger.ActionOwner = null;
                if (trigger.Rules != null)
                {
                    foreach (BaseRule r in trigger.Rules)
                    {
                        if (r != null)
                        {
                            r.ActionOwner = null;
                        }
                    }
                }
                for (int j = i; j < _supportedTriggers.arraySize - 1; j++)
                {
                    _supportedTriggers.MoveArrayElement(j + 1, j);
                }
                _supportedTriggers.arraySize--;
                break;
            }
        }
        EditorGUILayout.Space();
        EditorGUILayout.EndVertical();

        // Draw the rest of the control except several predefined fields or the fields which are marked as show first
        prop = serializedObject.GetIterator();

        prop.NextVisible(true);
        do
        {
            if (prop.name != "m_Script" && !ShouldShowFirst(prop))
            {
                EditorGUILayout.PropertyField(prop, true);
            }
        } while (prop.NextVisible(false));


        //Save changes to the Action Script
        serializedObject.ApplyModifiedProperties();
    }
Beispiel #49
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();
	}
Beispiel #50
0
        // -------------------------------------------------------------------------------

        public static object ShowInspectorForType(System.Type type, object value, string name)
        {
            if (type == typeof(bool))
            {
                return(EditorGUILayout.Toggle(name, (bool)value));
            }
            else if (type == typeof(string))
            {
                return(EditorGUILayout.TextField(name, (string)value));
            }
            else if (type == typeof(int))
            {
                return(EditorGUILayout.IntField(name, (int)value));
            }
            else if (type == typeof(float))
            {
                return(EditorGUILayout.FloatField(name, (float)value));
            }
            else if (type == typeof(Vector2))
            {
                return(EditorGUILayout.Vector2Field(name, (Vector2)value));
            }
            else if (type == typeof(Vector3))
            {
                return(EditorGUILayout.Vector3Field(name, (Vector3)value));
            }
            else if (typeof(Enum).IsAssignableFrom(type))
            {
                return(EditorGUILayout.EnumPopup(name, (Enum)value));
            }
            else if (typeof(IList <>).IsAssignableFrom(type))
            {
                EditorGUILayout.LabelField("TODO: LIST SUPPORT");
            }
            else if (typeof(UnityEngine.Object).IsAssignableFrom(type))
            {
                return(EditorGUILayout.ObjectField(name, (UnityEngine.Object)value, type,
                                                   typeof(Component).IsAssignableFrom(type) || type == typeof(GameObject) || type == typeof(UnityEngine.Object)));
            }
            else if (type.IsGenericType && typeof(Variable <>).IsAssignableFrom(type.GetGenericTypeDefinition()))
            {
                EditorGUILayout.BeginHorizontal();

                if (value == null)
                {
                    value = System.Activator.CreateInstance(type);
                }

                var variableBoundMemberNameField = GetPrivateFieldInfo(value, "mBoundMemberName");
                var variableBoundMemberName      = (string)variableBoundMemberNameField.GetValue(value);

                bool isBound = (variableBoundMemberName != null);
                if (!isBound)
                {
                    var variableValueField = GetPrivateFieldInfo(value, "mValue");
                    var variableValue      = variableValueField.GetValue(value);
                    var variableValuetype  = variableValueField.FieldType;

                    variableValueField.SetValue(value, ShowInspectorForType(variableValuetype, variableValue, name));
                }
                else
                {
                    var variableBoundOwnerField = GetPrivateFieldInfo(value, "mBoundOwner");
                    var variableBoundOwnerValue = (MonoBehaviour)variableBoundOwnerField.GetValue(value);

                    if (variableBoundOwnerValue != null)
                    {
                        string path = GetComponentPath(variableBoundOwnerValue);
                        EditorGUILayout.LabelField(name + ": " + path + "/" + variableBoundMemberName);
                    }
                    else
                    {
                        Debug.LogWarning("Bound value couldn't be found, the object may have been deleted? Unbinding...");
                        UnbindVariable(value);
                    }
                }

                if (GUILayout.Button("@", GUILayout.Width(20), GUILayout.Height(16)))
                {
                    var menu = new GenericMenu();
                    if (isBound)
                    {
                        menu.AddItem(new GUIContent("Unbind"), false, () => { UnbindVariable(value); });
                    }
                    else
                    {
                        // Grab a list of all the GameObjects at the root of the scene
                        List <GameObject> sceneGameObjects = new List <GameObject>();
                        SceneManager.GetActiveScene().GetRootGameObjects(sceneGameObjects);

                        var genericVariableType = type.GetGenericArguments()[0];

                        // Iterate over all the GameObjects at the root of the scene
                        foreach (var gameObject in sceneGameObjects)
                        {
                            // For each scene object, iterate over all components (and children's components)
                            // and look for any properties or fields that match our Variable's generic type
                            foreach (var component in gameObject.GetComponentsInChildren <Component>())
                            {
                                // GameObjects are special type because we can get at them from components..
                                var showComponentsForGameObjects = (genericVariableType == typeof(GameObject));

                                foreach (PropertyInfo componentPropertyInfo in component.GetType().GetProperties())
                                {
                                    var propertyType = componentPropertyInfo.PropertyType;

                                    // Do we actually want to bind to the gameObject property on a component, rather than the component itself?
                                    var bindGameObjectFromMonoBehaviour = (showComponentsForGameObjects && typeof(MonoBehaviour).IsAssignableFrom(propertyType));

                                    if (bindGameObjectFromMonoBehaviour || propertyType == genericVariableType || genericVariableType.IsAssignableFrom(propertyType))
                                    {
                                        var menuPath = "Properties/" + GetComponentPath(component) + "/" + componentPropertyInfo.Name;
                                        menu.AddItem(new GUIContent(menuPath), false, () =>
                                        {
                                            BindVariable(value, component, componentPropertyInfo);
                                        });
                                    }
                                }

                                foreach (FieldInfo componentFieldInfo in component.GetType().GetFields())
                                {
                                    var fieldType = componentFieldInfo.FieldType;
                                    var bindGameObjectFromComponent = (showComponentsForGameObjects && typeof(MonoBehaviour).IsAssignableFrom(fieldType));

                                    if (bindGameObjectFromComponent || fieldType == genericVariableType || genericVariableType.IsAssignableFrom(fieldType))
                                    {
                                        var menuPath = "Fields/" + GetComponentPath(component) + "/" + componentFieldInfo.Name;
                                        menu.AddItem(new GUIContent(menuPath), false, () =>
                                        {
                                            MemberInfo memberToBind = componentFieldInfo;

                                            // Do we actually want to bind to the gameObject property on a component, rather than the component itself?
                                            if (bindGameObjectFromComponent)
                                            {
                                                memberToBind = component.GetType().GetProperty("gameObject");
                                            }

                                            BindVariable(value, component, memberToBind);
                                        });
                                    }
                                }
                            }
                        }
                    }
                    menu.ShowAsContext();
                }

                EditorGUILayout.EndHorizontal();
            }
            else
            {
                EditorGUILayout.LabelField("Couldn't display inspector for '" + name + "' of type: " + type.ToString());
            }

            return(value);
        }
Beispiel #51
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));
    }
        static void OnItemGUI(int instanceID, Rect rect)
        {
            var instance = EditorUtility.InstanceIDToObject(instanceID) as GameObject;

            if (instance == null)
            {
                return;
            }

            var prefabInstance = instance.GetComponent <PEPrefabScript>();

            var isPrefab = PrefabUtility.GetPrefabParent(instance) && PEUtils.FindRootPrefab(instance) == instance;

            if (prefabInstance)
            {
                if (Event.current.type == EventType.Repaint && PEUtils.FindRootPrefab(Selection.activeGameObject) == instance && Selection.activeGameObject != instance)
                {
                    EditorGUI.DrawRect(rect, new Color(0, 1, 0, 0.25f));
                }
                bool rootPrefab = PrefabUtility.GetPrefabParent(prefabInstance.gameObject) == prefabInstance.Prefab;
                var  color      = GUI.color;
                GUI.color = rootPrefab ? Color.green : (Color.yellow);

                if (!prefabInstance.enabled)
                {
                    GUI.color = Color.white;
                }

                if (prefabInstance.Prefab == null)
                {
                    GUI.color = Color.red;
                }

                const int width = 15;
                var       br    = rect;
                br.height -= 2;
                br.y      += 2 / 2;
                br.x      += br.width - width;
                br.width   = width;

                var content = new GUIContent(PEResources.icon, prefabInstance.Prefab ? prefabInstance.Prefab.name : "Missiog prefab with guid: " + prefabInstance.PrefabGUID);
                var click   = GUI.Button(br, content, emptyStyle);

                GUI.color = color;

                var evt = Event.current;
                if (prefabInstance.Prefab && (evt.type == EventType.ContextClick || click || evt.type == EventType.MouseUp))
                {
                    var mousePos = evt.mousePosition;
                    if (br.Contains(mousePos))
                    {
                        var menu = new GenericMenu();
                        BuildMenu(menu, prefabInstance, rootPrefab);

                        menu.ShowAsContext();
                        evt.Use();
                    }
                }
            }
            else
            if (isPrefab)
            {
                var click = PEPrefs.AutoPrefabs;
                if (click)
                {
                    MakeNested(instance);
                }
            }
        }
Beispiel #53
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();
    }
Beispiel #54
0
        public override void Clicked(int button)
        {
            var window   = StateWindow.Get();
            var stateRow = (StateRow)this.row.target;
            int rowIndex = window.rowIndex[stateRow];
            var selected = this.row.table.rows.Where(x => x.selected).ToArray();

            if (Event.current.alt && stateRow.requirements.Length > 1)
            {
                int length = stateRow.requirements.Length;
                rowIndex += button == 1 ? -1 : 1;
                if (rowIndex < 0)
                {
                    rowIndex = length - 1;
                }
                if (rowIndex >= length)
                {
                    rowIndex = 0;
                }
                window.rowIndex[stateRow] = rowIndex;
                window.BuildTable();
                return;
            }
            if (!this.row.selected && button == 1)
            {
                this.delayedContext = true;
            }
            if (button == 0 || !this.row.selected)
            {
                if (Event.current.shift)
                {
                    var allRows    = this.row.table.rows;
                    int firstIndex = selected.Length < 1 ? allRows.Count - 1 : allRows.FindIndex(x => x == selected.First());
                    int lastIndex  = selected.Length < 1 ? 0 : allRows.FindIndex(x => x == selected.Last());
                    int current    = allRows.FindIndex(x => x == this.row);
                    int closest    = current.Closest(firstIndex, lastIndex);
                    foreach (var row in allRows.Skip(current.Min(closest)).Take(current.Distance(closest) + 1))
                    {
                        row.selected = !row.disabled;
                    }
                }
                else
                {
                    bool state = !this.row.selected;
                    if (!Event.current.control)
                    {
                        window.DeselectAll();
                    }
                    this.row.selected = state;
                }
            }
            else if (button == 1)
            {
                var    menu = new GenericMenu();
                string term = selected.Any(x => x.target is StateRow && !x.target.As <StateRow>().section.IsEmpty()) ? "Regroup" : "Group";
                menu.AddItem(term + " Selected", false, window.GroupSelected);
                if (selected.Count(x => !x.target.As <StateRow>().section.IsEmpty()) > 0)
                {
                    menu.AddItem("Ungroup Selected", false, window.UngroupSelected);
                }
                menu.AddItem("Selection/Invert", false, window.InvertSelection);
                menu.AddItem("Selection/Deselect All", false, window.DeselectAll);
                if (selected.Length == 1)
                {
                    menu.AddItem("Add Alternate Row", false, this.AddAlternativeRow, stateRow);
                    if (rowIndex != 0)
                    {
                        menu.AddItem("Remove Alternative Row", false, this.RemoveAlternativeRow, stateRow);
                    }
                }
                menu.ShowAsContext();
            }
            window.Repaint();
        }
Beispiel #55
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;
		}
	}
Beispiel #56
0
        public override void OnInspectorGUI()
        {
            if (GUILayout.Button("ADD"))
            {
                GenericMenu menu = new GenericMenu();
                menu.AddItem(new GUIContent("Keycodes"), false, AddAxis, -2);
                menu.AddItem(new GUIContent("Mouse/Horizontal"), false, AddAxis, 1);
                menu.AddItem(new GUIContent("Mouse/Vertical"), false, AddAxis, 0);
                menu.AddItem(new GUIContent("Mouse/Wheel"), false, AddAxis, 2);
                menu.AddItem(new GUIContent("Joystick/Left Horizontal"), false, AddAxis, 3);
                menu.AddItem(new GUIContent("Joystick/Left Vertical"), false, AddAxis, 4);
                menu.AddItem(new GUIContent("Joystick/Right Horizontal"), false, AddAxis, 5);
                menu.AddItem(new GUIContent("Joystick/Right Vertical"), false, AddAxis, 6);
                menu.AddItem(new GUIContent("Custom Axis"), false, AddAxis, -1);
                menu.ShowAsContext();
            }

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Key Axes", EditorStyles.boldLabel);


            for (int i = 0; i < _keyAxes.arraySize; i++)
            {
                SerializedProperty child = _keyAxes.GetArrayElementAtIndex(i);

                string label = _axis.keyAxes[i].ToString();
                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.PropertyField(child, new GUIContent(label), true);

                if (GUILayout.Button("X", GUILayout.Width(18), GUILayout.Height(18)))
                {
                    _axis.keyAxes.RemoveAt(i);
                    UpdateObject();
                    return;
                }

                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.Space();
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Non-Key Axes", EditorStyles.boldLabel);

            for (int i = 0; i < _nativeAxes.arraySize; i++)
            {
                SerializedProperty child = _nativeAxes.GetArrayElementAtIndex(i);

                string label = _axis.nativeAxes[i].GetEditorLabelName();
                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.PropertyField(child, new GUIContent(label), true);

                if (GUILayout.Button("X", GUILayout.Width(18), GUILayout.Height(18)))
                {
                    _axis.nativeAxes.RemoveAt(i);
                    UpdateObject();
                    return;
                }

                EditorGUILayout.EndHorizontal();


                string axisName = _axis.nativeAxes[i].GetAxisName();
                try
                {
                    UnityEngine.Input.GetAxis(axisName);
                }
                catch
                {
                    EditorGUILayout.HelpBox("Vous devez avoir un axe nommé " + axisName + " dans l'input natif de unity.", MessageType.Error);
                }
            }

            serializedObject.ApplyModifiedProperties();
        }
    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();
        }
    }
        private void DrawMaterialSettings()
        {
            string label = "Materials";
            string id    = "billboardeditor-materials";

            GEditorCommon.Foldout(label, false, id, () =>
            {
                GUI.enabled    = false;
                atlasMaterial  = EditorGUILayout.ObjectField("Atlas Material", atlasMaterial, typeof(Material), false) as Material;
                normalMaterial = EditorGUILayout.ObjectField("Normal Material", normalMaterial, typeof(Material), false) as Material;
                GUI.enabled    = true;
                EditorGUILayout.BeginHorizontal();
                srcColorProps = EditorGUILayout.TextField("Source Color", srcColorProps);
                if (GUILayout.Button(GEditorCommon.contextIconText, EditorStyles.label, GUILayout.Width(14)))
                {
                    GenericMenu menu = new GenericMenu();
                    if (SrcColorSuggestion.Count > 0)
                    {
                        menu.AddDisabledItem(new GUIContent("Suggestion"));
                        menu.AddSeparator(null);
                        for (int i = 0; i < SrcColorSuggestion.Count; ++i)
                        {
                            string s = SrcColorSuggestion[i];
                            menu.AddItem(
                                new GUIContent(s),
                                false,
                                () => { srcColorProps = s; RenderPreview(); });
                        }
                    }
                    else
                    {
                        menu.AddDisabledItem(new GUIContent("No suitable property found!"));
                    }
                    menu.ShowAsContext();
                }
                EditorGUILayout.EndHorizontal();
                //desColorProps = EditorGUILayout.TextField("Des Color", desColorProps);

                EditorGUILayout.BeginHorizontal();
                srcTextureProps = EditorGUILayout.TextField("Source Texture", srcTextureProps);
                if (GUILayout.Button(GEditorCommon.contextIconText, EditorStyles.label, GUILayout.Width(14)))
                {
                    GenericMenu menu = new GenericMenu();
                    if (SrcTextureSuggestion.Count > 0)
                    {
                        menu.AddDisabledItem(new GUIContent("Suggestion"));
                        menu.AddSeparator(null);
                        for (int i = 0; i < SrcTextureSuggestion.Count; ++i)
                        {
                            string s = SrcTextureSuggestion[i];
                            menu.AddItem(
                                new GUIContent(s),
                                false,
                                () => { srcTextureProps = s; RenderPreview(); });
                        }
                    }
                    else
                    {
                        menu.AddDisabledItem(new GUIContent("No suitable property found!"));
                    }
                    menu.ShowAsContext();
                }
                EditorGUILayout.EndHorizontal();
                //desTextureProps = EditorGUILayout.TextField("Des Texture", desTextureProps);
            });
        }
        /// <summary>
        /// Default buttons can't handle generic menus as a result so we have to make our own buttons. Below
        /// this is how it's done.
        /// </summary>
        private void DrawAddForgeButton()
        {
            Event current    = Event.current;
            Rect  buttonRect = GUILayoutUtility.GetRect(ScriptForgeLabels.addWidget, m_Styles.buttonLeft);
            int   controlID  = GUIUtility.GetControlID(ScriptForgeLabels.addWidget, FocusType.Keyboard, buttonRect);

            if (current.type == EventType.MouseDown && buttonRect.Contains(current.mousePosition))
            {
                m_AddForgeButtonSelected = true;
                GUIUtility.hotControl    = controlID;
                current.Use();
                Repaint();
            }

            if (current.type == EventType.MouseUp)
            {
                m_AddForgeButtonSelected = false;

                if (buttonRect.Contains(current.mousePosition) && GUIUtility.hotControl == controlID)
                {
                    GenericMenu menu = new GenericMenu();

                    Assembly assembly = Assembly.GetCallingAssembly();
                    Type[]   types    = assembly.GetTypes();

                    for (int i = 0; i < types.Length; i++)
                    {
                        if (!types[i].IsAbstract && typeof(Widget).IsAssignableFrom(types[i]))
                        {
                            bool hasInstance = false;

                            for (int x = 0; x < m_Target.Widgets.Count; x++)
                            {
                                if (m_Target.Widgets[x].GetType() == types[i])
                                {
                                    hasInstance = true;
                                    break;
                                }
                            }

                            // Get the menu path.
                            string path = types[i].Name;

                            // We don't want to show widgets that are required because they can never be removed.
                            if (System.Attribute.GetCustomAttribute(types[i], typeof(RequiredWidgetAttribute)) == null)
                            {
                                if (System.Attribute.GetCustomAttribute(types[i], typeof(InDevelopmentAttribute)) != null)
                                {
                                    path = "In Development/" + path;
                                }

                                if (hasInstance)
                                {
                                    menu.AddDisabledItem(new GUIContent(path));
                                }
                                else
                                {
                                    menu.AddItem(new GUIContent(path), false, OnWidgetAdded, types[i]);
                                }
                            }
                        }
                        menu.ShowAsContext();
                    }
                }
            }


            else if (m_AddForgeButtonSelected && current.type == EventType.MouseUp)
            {
                m_AddForgeButtonSelected = false;
                current.Use();
                GUIUtility.hotControl = 0;
                Repaint();
            }

            if (current.type == EventType.Repaint)
            {
                m_Styles.buttonLeft.Draw(buttonRect, ScriptForgeLabels.addWidget, isHover: m_AddForgeButtonSelected, isActive: m_AddForgeButtonSelected, on: false, hasKeyboardFocus: false);
            }
        }
        public override bool Render()
        {
            if (this.character == null)
            {
                return(false);
            }


            scroll = EditorGUILayout.BeginScrollView(scroll);
            bool delete = false;
            bool close  = false;

            EditorGUILayout.BeginVertical(EditorStyles.helpBox);

            EditorGUILayout.VerticalScope clickArea = new EditorGUILayout.VerticalScope();
            using (clickArea)
            {
                EditorGUILayout.BeginHorizontal();
                if (showUniqueControls)
                {
                    EditorGUI.BeginChangeCheck();
                    GUI.SetNextControlName("user");
                    GUIStyle style         = GUI.GetNameOfFocusedControl() == "user" ? EditorStyles.textField : EditorStyles.label;
                    string   charactername = EditorGUILayout.TextField(GUIContent.none, this.character._Name, style);

                    if (EditorGUI.EndChangeCheck())
                    {
                        Undo.RecordObject(UndoObject, "Modify Character");
                        this.character._Name = charactername;
                    }
                }
                else
                {
                    EditorGUILayout.LabelField(this.character._Name, EditorStyles.label);
                }

                if (this.parent != null)
                {
                    if (GUILayout.Button("Pop"))
                    {
                        this.Show();
                        TeamEditor teamEdit = Editor.CreateInstance <TeamEditor>();

                        teamEdit.Do(mission.FindTeam(character), mission);
                        teamEdit.SetParent(this.parent);
                        this.parent.auxWindow = teamEdit;
                        this.parent           = null;
                    }
                }

                if (GUILayout.Button("X"))
                {
                    Undo.RecordObject(UndoObject, "Remove Character");
                    if (this.parent != null)
                    {
                        TeamEditor teamEdit = Editor.CreateInstance <TeamEditor>();
                        teamEdit.Do(mission.FindTeam(this.character), mission);
                        teamEdit.SetParent(this.parent);
                        this.parent.auxWindow = teamEdit;
                        this.parent           = null;
                    }
                    else
                    {
                        this.Close();
                    }


                    DestroyImmediate(character.SpawnCondition, true);
                    mission.FindTeam(this.character).members.Remove(this.character);
                    mission.RefreshCharacterDictionary();
                }

                if (GUILayout.Button("Close", GUILayout.Width(55)))
                {
                    close = true;
                }

                EditorGUILayout.EndHorizontal();


                EditorGUI.BeginDisabledGroup(!showUniqueControls);
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.BeginHorizontal();
                Sprite spr = EditorGUILayout.ObjectField(GUIContent.none, this.character.UIIcon, typeof(Sprite), false, GUILayout.Width(75)) as Sprite;
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();
                if (EditorGUI.EndChangeCheck())
                {
                    this.character.UIIcon = spr;
                }
                EditorGUI.EndDisabledGroup();
                this.character.prefab = EditorGUILayout.ObjectField("Prefab", this.character.prefab, typeof(CharacterBody), false) as CharacterBody;
                GUILayout.Space(10);
                EditorGUILayout.LabelField("AI", EditorStyles.boldLabel);

                EditorGUI.indentLevel++;



                EditorGUI.BeginChangeCheck();
                AIBehaviour _behav = EditorGUILayout.ObjectField("Ai Behaviour", this.character.aiBehaviour, typeof(AIBehaviour), false) as AIBehaviour;
                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RecordObject(UndoObject, "Modify AI"); this.character.aiBehaviour = _behav;
                }


                if (this.character.aiBehaviour && mission != null)
                {
                    if (character.onStartPath.Count != 0)
                    {
                        if (GUILayout.Button("Modify Path"))
                        {
                            PathMaker.Begin(SetStartPath, character.onStartPath);
                        }
                    }
                    else
                    {
                        if (GUILayout.Button("Create Path"))
                        {
                            PathMaker.Begin(SetStartPath, new List <GridPosition>());
                        }
                    }
                }
                GUILayout.Space(10);
                EditorGUI.indentLevel--;
                if (mission != null)
                {
                    EditorGUILayout.Space();
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.Space();
                    Folds[0] = EditorGUILayout.Foldout(Folds[0], GUIContent.none);
                    GUILayout.Space(-40);
                    EditorGUILayout.LabelField("Spawning", EditorStyles.boldLabel);
                    GUILayout.FlexibleSpace();
                    EditorGUILayout.EndHorizontal();
                    if (Folds[0])
                    {
                        EditorGUI.indentLevel++;
                        EditorGUILayout.BeginHorizontal();
                        GUILayout.Space(18);
                        this.character.SpawnPositon.EditorField(mission, EditorTools.CurrentInspectedGrid, new GUIContent("Position"));
                        EditorGUILayout.EndHorizontal();


                        mission.ConditionSelector("Spawn Condition", ref ShowSpanwCondFold, ref character.SpawnCondition, ref currentSelectedCtype);

                        EditorGUI.BeginChangeCheck();
                        GameGrid.BlockDirections.FaceDirections dir = (GameGrid.BlockDirections.FaceDirections)EditorGUILayout.EnumPopup("Face direction:", character.SpawnDirection);

                        if (EditorGUI.EndChangeCheck())
                        {
                            Undo.RecordObject(UndoObject, "Change Direction"); character.SpawnDirection = dir;
                        }
                        EditorGUI.indentLevel--;
                    }
                }
            }

            Event e = Event.current;

            if (e.isMouse && e.button == 1 && clickArea.rect.Contains(e.mousePosition))
            {
                GenericMenu CreateMenu = new GenericMenu();
                if (CopyCharacter != null)
                {
                    CreateMenu.AddItem(new GUIContent("Paste Character Values"), false, Paste);
                }
                else
                {
                    CreateMenu.AddDisabledItem(new GUIContent("Paste Character Values"));
                }
                CreateMenu.AddItem(new GUIContent("Copy Character Values"), false, Copy);
                CreateMenu.ShowAsContext();
            }

            EditorGUI.BeginDisabledGroup(!showUniqueControls);

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.Space();
            Folds[1] = EditorGUILayout.Foldout(Folds[1], GUIContent.none);
            GUILayout.Space(-40);
            EditorGUILayout.LabelField("Stats", EditorStyles.boldLabel);
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            if (Folds[1])
            {
                EditorGUI.indentLevel++;
                if (statsEditor == null)
                {
                    statsEditor = new StatsEditor(character.stats, mission, UndoObject);
                }
                statsEditor.OnGUI();

                EditorGUI.indentLevel--;
            }
            EditorGUILayout.Space();
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.Space();
            Folds[2] = EditorGUILayout.Foldout(Folds[2], GUIContent.none);
            GUILayout.Space(-40);
            EditorGUILayout.LabelField("Inventory", EditorStyles.boldLabel);
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            if (Folds[2])
            {
                EditorGUI.BeginChangeCheck();

                for (int i = 0; i < character.inventroy.Items.Count; i++)
                {
                    if (!itemFolds.ContainsKey(character.inventroy.Items[i]))
                    {
                        RefreshDictionaries();
                        break;
                    }
                }

                EditorGUI.indentLevel++;
                EditorGUILayout.BeginHorizontal();
                int addItem = EditorGUILayout.Popup("Add Item", 0, EditorTools.ItemDatabase.ItemNames);
                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RecordObject(UndoObject, "Modify Inventory");
                    int index = character.inventroy.Items.FindIndex(a => a.item == EditorTools.ItemDatabase.items[addItem]);
                    if (index == -1)
                    {
                        character.inventroy.Items.Add(new ItemStack(EditorTools.ItemDatabase.items[addItem]));
                    }
                    else
                    {
                        character.inventroy.Items[index].amount++;
                    }
                }
                EditorGUI.BeginDisabledGroup(ItemEditor.CopiedItem == null);
                if (GUILayout.Button("Paste"))
                {
                    int index = character.inventroy.Items.FindIndex(a => a.item == ItemEditor.CopiedItem);
                    Undo.RecordObject(UndoObject, "Modify Inventory");
                    if (index == -1)
                    {
                        character.inventroy.Items.Add(new ItemStack(ItemEditor.CopiedItem));
                    }
                    else
                    {
                        character.inventroy.Items[index].amount++;
                    }
                }
                EditorGUI.EndDisabledGroup();
                EditorGUILayout.EndHorizontal();

                int deleteIndex = -1;
                for (int i = 0; i < character.inventroy.Items.Count; i++)
                {
                    if (itemFolds.ContainsKey(character.inventroy.Items[i]))
                    {
                        if (character.inventroy.Items[i].item == null)
                        {
                            character.inventroy.Items.RemoveAt(i);
                            continue;
                        }
                        EditorGUILayout.BeginHorizontal();
                        itemFolds[character.inventroy.Items[i]] = EditorGUILayout.Foldout(itemFolds[character.inventroy.Items[i]], character.inventroy.Items[i].item.ItemName);
                        character.inventroy.Items[i].amount     = EditorGUILayout.IntField(character.inventroy.Items[i].amount);

                        if (GUILayout.Button("X", GUILayout.Width(20)) || character.inventroy.Items[i].amount <= 0)
                        {
                            deleteIndex = i;
                        }

                        EditorGUILayout.EndHorizontal();
                        if (itemFolds[character.inventroy.Items[i]])
                        {
                            EditorGUI.indentLevel++;
                            cachedEditors[character.inventroy.Items[i]].OnInspectorGUI();
                            EditorGUI.indentLevel--;
                        }
                    }
                    else
                    {
                        RefreshDictionaries();
                    }
                }
                if (deleteIndex != -1)
                {
                    Undo.RecordObject(UndoObject, "Modify Inventory");
                    character.inventroy.Items.RemoveAt(deleteIndex);
                }
                EditorGUI.EndDisabledGroup();
                EditorGUI.indentLevel--;
            }
            if (GUI.changed && !Application.isPlaying)
            {
                EditorUtility.SetDirty(UndoObject);
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndScrollView();
            return(delete || close);
        }