コード例 #1
0
 public MenuItem(string _path, GUIContent _content, MenuFunctionData _func, object _userData)
 {
     path     = _path;
     content  = _content;
     funcData = _func;
     userData = _userData;
 }
コード例 #2
0
 public void Setup(string setLabel, string setTooltip, OnActivateItemWithParameter setEffect, object setEffectParameterValue, bool setOn)
 {
     label = GUIContentPool.Create(setLabel, setTooltip);
     effectWithParameter  = setEffect;
     effectParameterValue = setEffectParameterValue;
     on = setOn;
 }
コード例 #3
0
ファイル: BTHelper.cs プロジェクト: zyb2013/GameProject3
        public static void ShowComponentsSelectionMenu(Type baseType, Action <Type> callback)
        {
            UnityEditor.GenericMenu.MenuFunction2 select = (selectType) => { callback((Type)selectType); };
            UnityEditor.GenericMenu menu       = new UnityEditor.GenericMenu();
            List <NodeAttribute>    scriptList = new List <NodeAttribute>();

            Type [] subTypes = System.Reflection.Assembly.GetExecutingAssembly().GetTypes();
            for (int i = 0; i < subTypes.Length; i++)
            {
                Type type = subTypes[i];
                if (IsSubClassOf(type, baseType) && type.IsDefined(typeof(NodeAttribute), false))
                {
                    NodeAttribute[] attrs = (NodeAttribute[])type.GetCustomAttributes(typeof(NodeAttribute), false);
                    if (attrs != null && attrs.Length > 0)
                    {
                        NodeAttribute attr = attrs[0];
                        attr.NodeType = type;
                        scriptList.Add(attr);
                    }
                }
            }
            for (int i = 0; i < scriptList.Count; i++)
            {
                string label = scriptList[i].Label;
                string type  = scriptList[i].Type;
                menu.AddItem(new GUIContent(type + "/" + label), false, select, scriptList[i].NodeType);
            }
            menu.ShowAsContext();
        }
コード例 #4
0
        protected override void OnNodeInspectorGUI()
        {
            if (GUILayout.Button("Set GO TO Target"))
            {
                UnityEditor.GenericMenu.MenuFunction2 Selected = (object o) => {
                    _targetNode = (DTNode)o;
                };

                var menu = new UnityEditor.GenericMenu();
                foreach (DTNode node in graph.allNodes)
                {
                    if (node != this)
                    {
                        menu.AddItem(new GUIContent(node.name), false, Selected, node);
                    }
                }
                menu.ShowAsContext();
                Event.current.Use();
            }

            if (_targetNode != null && GUILayout.Button("Select Target Node"))
            {
                Graph.currentSelection = _targetNode;
            }
        }
コード例 #5
0
        protected override void OnNodeInspectorGUI()
        {
            if (GUILayout.Button("Set Target Node"))
            {
                UnityEditor.GenericMenu.MenuFunction2 Selected = (object o) =>
                {
                    _targetNode = (DTNode)o;
                };

                var menu = new UnityEditor.GenericMenu();
                foreach (DTNode node in graph.allNodes)
                {
                    if (node != this)
                    {
                        menu.AddItem(new GUIContent("#" + node.ID.ToString()), false, Selected, node);
                    }
                }
                menu.ShowAsContext();
                Event.current.Use();
            }

            if (_targetNode != null && GUILayout.Button("Select Target Node"))
            {
                NodeCanvas.Editor.GraphEditorUtility.activeElement = _targetNode;
            }
        }
コード例 #6
0
        public static ItemInfo Item(string label, string tooltip, OnActivateItemWithParameter effect, object onActiveItemParameterValue, bool on)
        {
            ItemInfo item;

            if (!ItemPool.TryGet(out item))
            {
                item = new ItemInfo();
            }
            item.Setup(label, tooltip, effect, onActiveItemParameterValue, on);
            return(item);
        }
コード例 #7
0
        public void AddItem(GUIContent content, bool on, MenuFunctionData func, object userData)
        {
#if UNITY_EDITOR
            if (editorMenu != null)
            {
                editorMenu.AddItem(content, on, func, userData);
            }
            else
#endif
            popup.AddItem(content, on, func, userData);
        }
コード例 #8
0
        ////////////////////////////////////////
        ///////////GUI AND EDITOR STUFF/////////
        ////////////////////////////////////////
                #if UNITY_EDITOR
        protected override void OnTaskInspectorGUI()
        {
            if (!Application.isPlaying && GUILayout.Button("Select Static Method"))
            {
                UnityEditor.GenericMenu.MenuFunction2 MethodSelected = (m) => {
                    SetMethod((MethodInfo)m);
                };

                var menu = new UnityEditor.GenericMenu();
                foreach (var t in UserTypePrefs.GetPreferedTypesList(typeof(object)))
                {
                    foreach (var m in t.GetMethods(BindingFlags.Static | BindingFlags.Public).OrderBy(m => !m.IsSpecialName))
                    {
                        if (m.IsGenericMethod)
                        {
                            continue;
                        }

                        menu.AddItem(new GUIContent(t.FriendlyName() + "/" + m.SignatureName()), false, MethodSelected, m);
                    }
                }
                if (NodeCanvas.Editor.NCPrefs.useBrowser)
                {
                    menu.ShowAsBrowser("Select Static Method", this.GetType());
                }
                else
                {
                    menu.ShowAsContext();
                }
                Event.current.Use();
            }


            if (targetMethod != null)
            {
                GUILayout.BeginVertical("box");
                UnityEditor.EditorGUILayout.LabelField("Type", targetMethod.DeclaringType.FriendlyName());
                UnityEditor.EditorGUILayout.LabelField("Method", targetMethod.Name);
                UnityEditor.EditorGUILayout.LabelField("Returns", targetMethod.ReturnType.FriendlyName());
                GUILayout.EndVertical();

                var paramNames = targetMethod.GetParameters().Select(p => p.Name.SplitCamelCase()).ToArray();
                for (var i = 0; i < paramNames.Length; i++)
                {
                    NodeCanvas.Editor.BBParameterEditor.ParameterField(paramNames[i], parameters[i]);
                }

                if (targetMethod.ReturnType != typeof(void))
                {
                    NodeCanvas.Editor.BBParameterEditor.ParameterField("Save Return Value", returnValue, true);
                }
            }
        }
コード例 #9
0
        public static void ShowMenu(Type type, UnityEditor.GenericMenu.MenuFunction2 menuFunction2)
        {
            UnityEditor.GenericMenu menu = new UnityEditor.GenericMenu();
            var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(item => item.GetTypes())
                        .Where(item => item.IsSubclassOf(type)).ToList();

            for (int i = 0; i < types.Count; i++)
            {
                Type t = types[i];
                menu.AddItem(new GUIContent(t.Name), false, menuFunction2, t);
            }
            menu.ShowAsContext();
        }
コード例 #10
0
        public void AddItem(GUIContent content, bool on, MenuFunctionData func, object userData)
        {
            string   path;
            MenuItem parent = AddHierarchy(ref content, out path);

            if (parent != null)
            {
                parent.subItems.Add(new MenuItem(path, content, func, userData));
            }
            else
            {
                menuItems.Add(new MenuItem(path, content, func, userData));
            }
        }
コード例 #11
0
            public void Dispose()
            {
                if (label == GUIContent.none)
                {
                    label = null;
                }
                else
                {
                    GUIContentPool.Dispose(ref label);
                }

                methodOwner          = null;
                on                   = false;
                effect               = null;
                effectWithParameter  = null;
                effectParameterValue = null;
                isSeparator          = false;
            }
コード例 #12
0
        ///----------------------------------------------------------------------------------------------

        ///Graph events AFTER nodes
        static void HandlePostNodesGraphEvents(Graph graph, Vector2 canvasMousePos)
        {
            //Shortcuts
            if (GUIUtility.keyboardControl == 0)
            {
                //Copy/Cut/Paste
                if (e.type == EventType.ValidateCommand || e.type == EventType.Used)
                {
                    if (e.commandName == "Copy" || e.commandName == "Cut")
                    {
                        List <Node> selection = null;
                        if (GraphEditorUtility.activeNode != null)
                        {
                            selection = new List <Node> {
                                GraphEditorUtility.activeNode
                            };
                        }
                        if (GraphEditorUtility.activeElements != null && GraphEditorUtility.activeElements.Count > 0)
                        {
                            selection = GraphEditorUtility.activeElements.Cast <Node>().ToList();
                        }
                        if (selection != null)
                        {
                            CopyBuffer.Set <Node[]>(Graph.CloneNodes(selection).ToArray());
                            if (e.commandName == "Cut")
                            {
                                foreach (Node node in selection)
                                {
                                    graph.RemoveNode(node);
                                }
                            }
                        }
                        e.Use();
                    }
                    if (e.commandName == "Paste")
                    {
                        if (CopyBuffer.Has <Node[]>())
                        {
                            TryPasteNodesInGraph(graph, CopyBuffer.Get <Node[]>(), canvasMousePos + new Vector2(500, 500) / graph.zoomFactor);
                        }
                        e.Use();
                    }
                }

                if (e.type == EventType.KeyUp)
                {
                    //Delete
                    if (e.keyCode == KeyCode.Delete || e.keyCode == KeyCode.Backspace)
                    {
                        if (GraphEditorUtility.activeElements != null && GraphEditorUtility.activeElements.Count > 0)
                        {
                            foreach (var obj in GraphEditorUtility.activeElements.ToArray())
                            {
                                if (obj is Node)
                                {
                                    graph.RemoveNode(obj as Node);
                                }
                                if (obj is Connection)
                                {
                                    graph.RemoveConnection(obj as Connection);
                                }
                            }
                            GraphEditorUtility.activeElements = null;
                        }

                        if (GraphEditorUtility.activeNode != null)
                        {
                            graph.RemoveNode(GraphEditorUtility.activeNode);
                            GraphEditorUtility.activeElement = null;
                        }

                        if (GraphEditorUtility.activeConnection != null)
                        {
                            graph.RemoveConnection(GraphEditorUtility.activeConnection);
                            GraphEditorUtility.activeElement = null;
                        }
                        e.Use();
                    }

                    //Duplicate
                    if (e.keyCode == KeyCode.D && e.control && !e.alt)
                    {
                        if (GraphEditorUtility.activeElements != null && GraphEditorUtility.activeElements.Count > 0)
                        {
                            TryPasteNodesInGraph(graph, GraphEditorUtility.activeElements.OfType <Node>().ToArray(), default(Vector2));
                        }
                        if (GraphEditorUtility.activeNode != null)
                        {
                            GraphEditorUtility.activeElement = GraphEditorUtility.activeNode.Duplicate(graph);
                        }
                        //Connections can't be duplicated by themselves. They do so as part of multiple node duplication.
                        e.Use();
                    }
                }
            }

            //No panel is obscuring
            if (GraphEditorUtility.allowClick)
            {
                #region 自定义快捷键

                if ((currentGraph.GetType() == typeof(FlowGraph) || currentGraph.GetType().IsSubclassOf(typeof(FlowGraph))) && GUIUtility.keyboardControl == 0)
                {
                    if (e.keyCode == KeyCode.F && e.control && !e.alt)
                    {
                        //Debug.Log("ctrl +f ");

                        FindNode toolNode = currentGraph.GetAllNodesOfType <FindNode>().FirstOrDefault();
                        if (toolNode != null)
                        {
                            NodeCanvas.Editor.GraphEditorUtility.activeElement = toolNode;
                        }
                        else
                        {
                            FindNode newNode = currentGraph.AddNode <FindNode>(ViewToCanvas(e.mousePosition));

                            NodeCanvas.Editor.GraphEditorUtility.activeElement = newNode;
                            //Debug.Log("There is no Find Node,Create a new node!");
                        }
                        //e.Use();
                    }


                    if (e.keyCode == KeyCode.A && e.control && !e.alt && !e.shift)
                    {
                        NodeCanvas.Editor.GraphEditorUtility.activeElements = null;
                        NodeCanvas.Editor.GraphEditorUtility.activeElement  = null;

                        if (currentGraph.allNodes == null)
                        {
                            return;
                        }

                        if (currentGraph.allNodes.Count > 1)
                        {
                            NodeCanvas.Editor.GraphEditorUtility.activeElements = currentGraph.allNodes.Cast <object>().ToList();
                            //e.Use();
                            return;
                        }
                        else
                        {
                            NodeCanvas.Editor.GraphEditorUtility.activeElement = currentGraph.allNodes[0];
                            //e.Use();
                        }
                    }
                    if (e.keyCode == KeyCode.C && e.type == EventType.KeyUp && !e.control && !e.alt && !e.shift && GUIUtility.keyboardControl == 0)
                    {
                        if (GraphEditorUtility.activeElement != null ||
                            GraphEditorUtility.activeElements != null && GraphEditorUtility.activeElements.Count > 0)
                        {
                            List <Node> node = new List <Node>();
                            if (GraphEditorUtility.activeElement != null)
                            {
                                node.Add((Node)GraphEditorUtility.activeElement);
                            }
                            else
                            {
                                node = GraphEditorUtility.activeElements.Cast <Node>().ToList();
                            }

                            Undo.RegisterCompleteObjectUndo(currentGraph, "Create Group");
                            if (currentGraph.canvasGroups == null)
                            {
                                currentGraph.canvasGroups = new List <Framework.CanvasGroup>();
                            }
                            Framework.CanvasGroup group = new Framework.CanvasGroup(GetNodeBounds(node).ExpandBy(100f), "New Canvas Group");
                            currentGraph.canvasGroups.Add(group);
                            group.isRenaming = true;
                        }
                    }
                    if (e.keyCode == KeyCode.G && !e.control && !e.alt && e.shift && GUIUtility.keyboardControl == 0)
                    {
                        if (NodeCanvas.Editor.GraphEditorUtility.activeElements == null ||
                            NodeCanvas.Editor.GraphEditorUtility.activeElements.Count < 2 && NodeCanvas.Editor.GraphEditorUtility.activeElement != null &&
                            NodeCanvas.Editor.GraphEditorUtility.activeElement.GetType() == typeof(MacroNodeWrapper))
                        {
                            //Debug.Log("current select is group node");
                            MacroNodeWrapper n = (MacroNodeWrapper)NodeCanvas.Editor.GraphEditorUtility.activeElement;

                            if (n.macro.allNodes.Count <= 2)
                            {
                                return;
                            }
                            List <Node> childNode = new List <Node>();

                            foreach (var c in n.macro.allNodes)
                            {
                                if (c.GetType() != typeof(MacroInputNode) && c.GetType() != typeof(MacroOutputNode))
                                {
                                    childNode.Add(c);
                                }
                            }

                            var newNodes = Graph.CopyNodesToGraph(childNode, currentGraph);

                            currentGraph.RemoveNode(n);
                            NodeCanvas.Editor.GraphEditorUtility.activeElement = null;

                            if (NodeCanvas.Editor.GraphEditorUtility.activeElements != null)
                            {
                                NodeCanvas.Editor.GraphEditorUtility.activeElements = newNodes.Cast <object>().ToList();
                            }
                        }
                    }

                    if (e.keyCode == KeyCode.G && e.control && !e.alt && !e.shift && GUIUtility.keyboardControl == 0)
                    {
                        //Debug.Log("ctrl +g ");
                        if (NodeCanvas.Editor.GraphEditorUtility.activeElements == null || NodeCanvas.Editor.GraphEditorUtility.activeElements.Count < 1)
                        {
                            //e.Use();
                            return;
                        }

                        List <Node> ns            = NodeCanvas.Editor.GraphEditorUtility.activeElements.Cast <Node>().ToList();
                        Rect        groupNodeRect = GetNodeBounds(ns, viewRect, false);
                        var         wrapper       = currentGraph.AddNode <MacroNodeWrapper>(groupNodeRect.center);
                        wrapper.macro              = NestedUtility.CreateBoundNested <GroupMacro>(wrapper, currentGraph);
                        wrapper.macro.name         = "NewGroup";
                        wrapper.macro.CategoryPath = (currentGraph.agent != null ? currentGraph.agent.name : currentGraph.name) + "/";
                        wrapper.macro.agent        = currentGraph.agent;

                        wrapper.macro.entry.position = new Vector2(groupNodeRect.x - 200f,
                                                                   groupNodeRect.y + 0.5f * groupNodeRect.height);
                        wrapper.macro.exit.position = new Vector2(groupNodeRect.x + groupNodeRect.width + 100f,
                                                                  groupNodeRect.y + 0.5f * groupNodeRect.height);

                        wrapper.macro.translation = -groupNodeRect.center + new Vector2(500f, 500f);

                        Graph.CopyNodesToGraph(NodeCanvas.Editor.GraphEditorUtility.activeElements.OfType <Node>().ToList(), wrapper.macro);

                        foreach (var c in ns)
                        {
                            currentGraph.RemoveNode(c);
                        }
                        NodeCanvas.Editor.GraphEditorUtility.activeElements.Clear();
                        NodeCanvas.Editor.GraphEditorUtility.activeElement = wrapper;
                    }
                    if (e.type == EventType.KeyDown && e.keyCode == KeyCode.I && GUIUtility.keyboardControl == 0)
                    {
                        List <Node> allNodes = currentGraph.GetAllNodesOfType <Node>();
                        if (allNodes != null && allNodes.Count < 2)
                        {
                            return;
                        }

                        if (NodeCanvas.Editor.GraphEditorUtility.activeElement != null)
                        {
                            if (allNodes.Contains((Node)NodeCanvas.Editor.GraphEditorUtility.activeElement))
                            {
                                allNodes.Remove((Node)NodeCanvas.Editor.GraphEditorUtility.activeElement);
                                NodeCanvas.Editor.GraphEditorUtility.activeElement = null;
                                NodeCanvas.Editor.GraphEditorUtility.activeElements.Clear();
                                NodeCanvas.Editor.GraphEditorUtility.activeElements = allNodes.Cast <object>().ToList();
                            }
                            return;
                        }

                        if (NodeCanvas.Editor.GraphEditorUtility.activeElements != null && NodeCanvas.Editor.GraphEditorUtility.activeElements.Count > 1)
                        {
                            List <object> invertNodeList = NodeCanvas.Editor.GraphEditorUtility.activeElements;
                            invertNodeList.ForEach(x =>
                            {
                                if (allNodes.Contains((Node)x))
                                {
                                    allNodes.Remove((Node)x);
                                }
                            });
                            NodeCanvas.Editor.GraphEditorUtility.activeElements.Clear();
                            if (allNodes.Count == 0)
                            {
                                NodeCanvas.Editor.GraphEditorUtility.activeElement = null;
                            }
                            else if (allNodes.Count == 1)
                            {
                                NodeCanvas.Editor.GraphEditorUtility.activeElement = allNodes[0];
                            }
                            else
                            {
                                NodeCanvas.Editor.GraphEditorUtility.activeElements = allNodes.Cast <object>().ToList();
                            }

                            return;
                        }
                        e.Use();
                    }
                    if (e.type == EventType.KeyUp && e.alt && e.control)
                    {
                        //Type genericType;

                        UnityEditor.GenericMenu.MenuFunction2 S = (obj) =>
                        {
                            NodeCanvas.Editor.GraphEditorUtility.activeElement = GraphEditor.currentGraph.AddNode(obj.GetType(),
                                                                                                                  ViewToCanvas(e.mousePosition));
                        };

                        UnityEditor.GenericMenu.MenuFunction2 D = (obj) =>
                        {
                            var genericT = typeof(SimplexNodeWrapper <>).MakeGenericType(obj.GetType());
                            NodeCanvas.Editor.GraphEditorUtility.activeElement = GraphEditor.currentGraph.AddNode(genericT, ViewToCanvas(e.mousePosition));
                        };


                        if (e.keyCode == KeyCode.S)
                        {
                            var menu = new UnityEditor.GenericMenu();

                            menu.AddItem(new GUIContent("Split"), false, S, new Split());
                            menu.AddItem(new GUIContent("Sequence"), false, S, new Sequence());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("SetActive"), false, D, new S_Active());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("SendEvent"), false, D, new SendEvent());
                            menu.AddItem(new GUIContent("SendEvent<T>"), false, D, new SendEvent <object>());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("Self"), false, S, new OwnerVariable());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("SwitchByIndex"), false, S, new Switch <object>());
                            menu.AddItem(new GUIContent("Switch Value"), false, D, new SwitchValue <object>());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("SwitchFlow/Switch Bool"), false, S, new SwitchBool());
                            menu.AddItem(new GUIContent("SwitchFlow/Switch String"), false, S, new SwitchString());
                            menu.AddItem(new GUIContent("SwitchFlow/Switch Int"), false, S, new SwitchInt());
                            menu.AddItem(new GUIContent("SwitchFlow/Switch Enum"), false, S, new SwitchEnum());
                            menu.AddItem(new GUIContent("SwitchFlow/Switch Tag"), false, S, new SwitchTag());
                            menu.AddItem(new GUIContent("SwitchFlow/Switch Comparison"), false, S, new SwitchComparison());

                            menu.ShowAsContext();
                            //e.Use();
                            return;
                        }

                        if (e.keyCode == KeyCode.A)
                        {
                            var menu = new UnityEditor.GenericMenu();

                            menu.AddItem(new GUIContent("Awake"), false, S, new ConstructionEvent());
                            menu.AddItem(new GUIContent("OnEnable"), false, S, new EnableEvent());
                            menu.AddItem(new GUIContent("Start"), false, S, new StartEvent());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("Update"), false, S, new UpdateEvent());
                            menu.AddItem(new GUIContent("FixedUpdate"), false, S, new FixedUpdateEvent());
                            menu.AddItem(new GUIContent("LateUpdate"), false, S, new LateUpdateEvent());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("OnDisable"), false, S, new DisableEvent());
                            menu.ShowAsContext();
                            return;
                        }
                        if (e.keyCode == KeyCode.C)
                        {
                            var menu = new UnityEditor.GenericMenu();
                            menu.AddItem(new GUIContent("Cache"), false, D, new Cache <object>());

                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("Coroutine"), false, S, new CoroutineState());
                            menu.AddItem(new GUIContent("Cooldown"), false, S, new Cooldown());
                            menu.AddItem(new GUIContent("Chance"), false, S, new Chance());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("CustomEvent"), false, S, new CustomEvent());
                            menu.AddItem(new GUIContent("CustomEvent<T>"), false, S, new CustomEvent <object>());

                            menu.ShowAsContext();
                            return;
                        }

                        if (e.keyCode == KeyCode.E)
                        {
                            var menu = new UnityEditor.GenericMenu();
                            menu.AddItem(new GUIContent("KeyBoard"), false, S, new KeyboardEvents());
                            menu.AddItem(new GUIContent("UnityEventAutoCallbackEvent"), false, S, new UnityEventAutoCallbackEvent());
                            menu.AddItem(new GUIContent("CSharpAutoCallbackEvent"), false, S, new CSharpAutoCallbackEvent());
                            menu.AddItem(new GUIContent("DelegateCallbackEvent"), false, S, new DelegateCallbackEvent());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("UnityEventCallbackEvent"), false, S, new UnityEventCallbackEvent());
                            menu.AddItem(new GUIContent("CSharpEventCallback"), false, S, new CSharpEventCallback());
                            menu.ShowAsContext();
                            return;
                        }
                        if (e.keyCode == KeyCode.D)
                        {
                            var menu = new UnityEditor.GenericMenu();

                            menu.AddItem(new GUIContent("Debug log OnScreen"), false, S, new G_LogOnScreen());
                            menu.AddItem(new GUIContent("Debug log"), false, D, new LogText());
                            menu.AddItem(new GUIContent("Debug Event"), false, D, new DebugEvent());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("DummyFlow"), false, S, new Dummy());
                            menu.AddItem(new GUIContent("DummyValue"), false, D, new Identity <object>());

                            menu.AddItem(new GUIContent("DoOnce"), false, S, new DoOnce());
                            menu.ShowAsContext();
                            e.Use();
                        }

                        if (e.keyCode == KeyCode.R)
                        {
                            var menu = new UnityEditor.GenericMenu();

                            menu.AddItem(new GUIContent("RelayFlowInput"), false, S, new RelayFlowInput());
                            menu.AddItem(new GUIContent("RelayFlowOutput"), false, S, new RelayFlowOutput());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("RelayValueInput"), false, S, new RelayValueInput <object>());
                            menu.AddItem(new GUIContent("RelayValueOutput"), false, S, new RelayValueOutput <object>());

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

                        if (e.keyCode == KeyCode.W)
                        {
                            var menu = new UnityEditor.GenericMenu();

                            menu.AddItem(new GUIContent("Wait"), false, D, new Wait());
                            menu.AddItem(new GUIContent("While"), false, S, new While());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("WaitForOneFrame"), false, D, new WaitForOneFrame());
                            menu.AddItem(new GUIContent("WaitForEndOfFrame"), false, D, new FlowCanvas.Nodes.WaitForEndOfFrame());
                            menu.AddItem(new GUIContent("WaitForFixedUpdate"), false, D, new WaitForFixedUpdate());
                            menu.AddItem(new GUIContent("WaitForPhysicsFrame"), false, D, new WaitForPhysicsFrame());
                            menu.ShowAsContext();
                            e.Use();
                        }

                        if (e.keyCode == KeyCode.F)
                        {
                            Selection.activeGameObject = null;  //防止快捷键冲突
                            var menu = new UnityEditor.GenericMenu();
                            menu.AddItem(new GUIContent("Find"), false, D, new G_FindGameObject());
                            menu.AddItem(new GUIContent("FindChild"), false, D, new G_FindChild());
                            menu.AddItem(new GUIContent("FindGameObjectWithTag"), false, D, new G_FindGameObjectWithTag());
                            menu.AddItem(new GUIContent("FindGameObjectsWithTag"), false, D, new G_FindGameObjectsWithTag());
                            menu.AddItem(new GUIContent("FindObjectOfType"), false, D, new FindObjectOfType());
                            menu.AddItem(new GUIContent("FindObjectsOfType"), false, D, new FindObjectsOfType());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("Finish"), false, S, new Finish());
                            menu.AddItem(new GUIContent("CustomFunction"), false, S, new CustomFunctionEvent());
                            menu.AddItem(new GUIContent("CallCustomFunction"), false, S, new CustomFunctionCall());
                            menu.AddItem(new GUIContent("CallCustomFunction(CustomPort)"), false, S, new FunctionCall());
                            menu.AddItem(new GUIContent("FunctionCustomReturn"), false, S, new Return());

                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("ForLoop"), false, S, new ForLoop());
                            menu.AddItem(new GUIContent("ForEach"), false, S, new ForEach <float>());
                            menu.AddItem(new GUIContent("FlipFlop"), false, S, new FlipFlop());

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

                        if (e.keyCode == KeyCode.G)
                        {
                            var menu = new UnityEditor.GenericMenu();
                            menu.AddItem(new GUIContent("GetName"), false, D, new G_Name());
                            menu.AddItem(new GUIContent("GetAcive"), false, D, new G_Active());
                            menu.AddItem(new GUIContent("GetPosition"), false, D, new G_Position());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("GetChildByIndex"), false, D, new G_Child());
                            menu.AddItem(new GUIContent("GetChildCount"), false, D, new G_ChildCount());
                            menu.AddSeparator("");
                            menu.AddItem(new GUIContent("GetComponentByType"), false, D, new G_Component());
                            menu.AddItem(new GUIContent("GetComponentsByType"), false, D, new G_Components());
                            menu.AddItem(new GUIContent("GetComponentByName"), false, D, new G_ComponentByTypeName());
                            menu.AddItem(new GUIContent("GetComponentsInChildren"), false, D, new G_ComponentsInChildren());
                            menu.AddItem(new GUIContent("GetComponentInChildren"), false, D, new G_ComponentInChildren());
                            menu.AddItem(new GUIContent("GetComponentInParent"), false, D, new G_ComponentInParent());

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

                    if (e.type == EventType.KeyUp && e.alt)
                    {
                        Type genericType;

                        switch (e.keyCode)
                        {
                        case KeyCode.Alpha1:
                            genericType = typeof(GetVariable <>).MakeGenericType(typeof(float));
                            break;

                        case KeyCode.Alpha2:
                            genericType = typeof(GetVariable <>).MakeGenericType(typeof(Vector2));
                            break;

                        case KeyCode.Alpha3:
                            genericType = typeof(GetVariable <>).MakeGenericType(typeof(Vector3));
                            break;

                        case KeyCode.Alpha4:
                            genericType = typeof(GetVariable <>).MakeGenericType(typeof(Quaternion));
                            break;

                        case KeyCode.Alpha5:
                            genericType = typeof(GetVariable <>).MakeGenericType(typeof(Color));
                            break;

                        default:
                            //genericType = typeof(GetVariable<>).MakeGenericType(typeof(float));
                            return;
                            //break;
                        }

                        var varN = (FlowNode)GraphEditor.currentGraph.AddNode(genericType);
                        varN.position = ViewToCanvas(e.mousePosition - varN.rect.center * 0.5f);

                        NodeCanvas.Editor.GraphEditorUtility.activeElement = varN;

                        e.Use();
                    }
                }
                if (e.type == EventType.KeyDown && e.keyCode == KeyCode.F && GUIUtility.keyboardControl == 0)
                {
                    FocusSelection();
                }

                #endregion


                //'Tilt' or 'Space' keys, opens up the complete context menu browser
                if (e.type == EventType.KeyDown && !e.shift && (e.keyCode == KeyCode.BackQuote || e.keyCode == KeyCode.Space))
                {
                    GenericMenuBrowser.Show(GetAddNodeMenu(graph, canvasMousePos), e.mousePosition, string.Format("Add {0} Node", graph.GetType().FriendlyName()), graph.baseNodeType);
                    e.Use();
                }

                //Right click canvas context menu. Basicaly for adding new nodes.
                if (e.type == EventType.ContextClick)
                {
                    var menu = GetAddNodeMenu(graph, canvasMousePos);
                    if (CopyBuffer.Has <Node[]>() && CopyBuffer.Peek <Node[]>()[0].GetType().IsSubclassOf(graph.baseNodeType))
                    {
                        menu.AddSeparator("/");
                        var copiedNodes = CopyBuffer.Get <Node[]>();
                        if (copiedNodes.Length == 1)
                        {
                            menu.AddItem(new GUIContent(string.Format("Paste Node ({0})", copiedNodes[0].GetType().FriendlyName())), false, () => { TryPasteNodesInGraph(graph, copiedNodes, canvasMousePos); });
                        }
                        else if (copiedNodes.Length > 1)
                        {
                            menu.AddItem(new GUIContent(string.Format("Paste Nodes ({0})", copiedNodes.Length.ToString())), false, () => { TryPasteNodesInGraph(graph, copiedNodes, canvasMousePos); });
                        }
                    }

                    if (NCPrefs.useBrowser)
                    {
                        menu.ShowAsBrowser(e.mousePosition, string.Format("Add {0} Node", graph.GetType().FriendlyName()), graph.baseNodeType);
                    }
                    else
                    {
                        menu.ShowAsContext();
                    }
                    e.Use();
                }
            }
        }
コード例 #13
0
 public static bool ButtonWithDropdownList(UnityEngine.GUIContent content, string[] buttonNames, UnityEditor.GenericMenu.MenuFunction2 callback, params UnityEngine.GUILayoutOption[] options)
 {
     if (__ButtonWithDropdownList_1_4 == null)
     {
         __ButtonWithDropdownList_1_4 = (Func <UnityEngine.GUIContent, string[], UnityEditor.GenericMenu.MenuFunction2, UnityEngine.GUILayoutOption[], bool>)Delegate.CreateDelegate(typeof(Func <UnityEngine.GUIContent, string[], UnityEditor.GenericMenu.MenuFunction2, UnityEngine.GUILayoutOption[], bool>), null, UnityTypes.UnityEditor_EditorGUI.GetMethod("ButtonWithDropdownList", R.StaticMembers, null, new Type[] { typeof(UnityEngine.GUIContent), typeof(string[]), typeof(UnityEditor.GenericMenu.MenuFunction2), typeof(UnityEngine.GUILayoutOption[]) }, null));
     }
     return(__ButtonWithDropdownList_1_4(content, buttonNames, callback, options));
 }
コード例 #14
0
 public void Add(string label, string tooltip, OnActivateItemWithParameter effect, object onActiveItemParameterValue, bool on)
 {
     Add(Item(label, tooltip, effect, onActiveItemParameterValue, on));
 }
コード例 #15
0
 public void Add(string label, OnActivateItemWithParameter effect, object onActiveItemParameterValue)
 {
     Add(Item(label, "", effect, onActiveItemParameterValue));
 }
コード例 #16
0
ファイル: FlowGraph.cs プロジェクト: wtrd1234/GameProject3
        //Create and set a UnityObject variable node on drop
        protected override void OnDropAccepted(Object o, Vector2 mousePos)
        {
            if (UnityEditor.EditorUtility.IsPersistent(this) && !UnityEditor.EditorUtility.IsPersistent(o))
            {
                Debug.LogError("This Graph is an asset. The dragged object is a scene reference. The reference will not persist");
            }

            if (o is Macro)
            {
                var mWrapper = AddNode <MacroNodeWrapper>(mousePos);
                mWrapper.macro = (Macro)o;
                return;
            }

            //Add as Variable
            UnityEditor.GenericMenu.MenuFunction2 SelectedVar = (obj) => {
                var genericType = typeof(GetVariable <>).MakeGenericType(new System.Type[] { obj.GetType() });
                var varNode     = (VariableNode)AddNode(genericType, mousePos);
                varNode.SetVariable(obj);
            };

            //Add as actions/function
            UnityEditor.GenericMenu.MenuFunction2 SelectedMethod = (m) => {
                var wrapper = AddNode <ReflectedMethodNodeWrapper>(mousePos);

                //draged source was game object. get the component of the method selected
                if (o is GameObject)
                {
                    o = (o as GameObject).GetComponent(((MethodInfo)m).ReflectedType);
                }

                //same as agent? revert to using "self"
                if (agent != null && o is Component && (o as Component).gameObject == agent.gameObject)
                {
                    o = null;
                }

                wrapper.SetMethod((MethodInfo)m, o);
            };

            var menu = new UnityEditor.GenericMenu();

            if (o is GameObject)
            {
                menu.AddItem(new GUIContent("Graph Variable (GameObject)"), false, SelectedVar, o);
                menu.AddSeparator("/");
                foreach (var component in (o as GameObject).GetComponents <Component>().Where(c => c.hideFlags == 0))
                {
                    var type     = component.GetType();
                    var category = type.Name + "/";
                    menu.AddItem(new GUIContent(string.Format(category + "Graph Variable ({0})", type.Name)), false, SelectedVar, component);


                    var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).ToList();
                    methods.AddRange(type.GetExtensionMethods());
                    foreach (var m in methods.OrderBy(m => !m.IsStatic).OrderBy(m => m.IsSpecialName).OrderBy(m => m.DeclaringType != type))
                    {
                        if (!m.IsGenericMethod)
                        {
                            var categoryName = category + (m.IsSpecialName? "Properties/" : "Methods/");
                            if (m.DeclaringType != type)
                            {
                                categoryName += "More/";
                            }
                            var name = categoryName + m.SignatureName();
                            var icon = UnityEditor.EditorGUIUtility.ObjectContent(null, type).image;
                            menu.AddItem(new GUIContent(name, icon), false, SelectedMethod, m);
                        }
                    }
                }
            }
            else
            {
                var type = o.GetType();
                menu.AddItem(new GUIContent(string.Format("Graph Variable ({0})", o.GetType().Name)), false, SelectedVar, o);
                var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).ToList();
                methods.AddRange(type.GetExtensionMethods());
                foreach (var m in methods.OrderBy(m => !m.IsStatic).OrderBy(m => m.IsSpecialName).OrderBy(m => m.DeclaringType != type))
                {
                    if (!m.IsGenericMethod)
                    {
                        var categoryName = (m.IsSpecialName? "Properties/" : "Methods/");
                        if (m.DeclaringType != type)
                        {
                            categoryName += "More/";
                        }
                        var name = categoryName + m.SignatureName();
                        var icon = UnityEditor.EditorGUIUtility.ObjectContent(null, type).image;
                        menu.AddItem(new GUIContent(name, icon), false, SelectedMethod, m);
                    }
                }
            }

            menu.ShowAsContext();
            Event.current.Use();
        }
コード例 #17
0
ファイル: FlowGraph.cs プロジェクト: wtrd1234/GameProject3
        //Append menu items in canvas right click context menu
        protected override UnityEditor.GenericMenu OnCanvasContextMenu(UnityEditor.GenericMenu menu, Vector2 mousePos)
        {
            //SimplexNode Wrapper
            System.Action <System.Type> SelectedSimplexNode = delegate(System.Type t){
                var genericType = typeof(SimplexNodeWrapper <>).MakeGenericType(new System.Type[] { (System.Type)t });
                AddNode(genericType, mousePos);
            };

            //MethodInfo Wrapper
            UnityEditor.GenericMenu.MenuFunction2 SelectedMethod = delegate(object m){
                var methodWrapper = AddNode <ReflectedMethodNodeWrapper>(mousePos);
                methodWrapper.SetMethod((MethodInfo)m);
            };

/*
 *                      //FieldInfo Wrapper
 *                      UnityEditor.GenericMenu.MenuFunction2 SelectedFieldGet = delegate(object f){
 *                              var fieldWrapper = AddNode<ReflectedFieldNodeWrapper>(mousePos);
 *                              fieldWrapper.SetField((FieldInfo)f, true);
 *                      };
 */
            //Macro Wrapper
            UnityEditor.GenericMenu.MenuFunction2 SelectedMacro = delegate(object m){
                var macroWrapper = AddNode <MacroNodeWrapper>(mousePos);
                macroWrapper.macro = (Macro)m;
            };


            //Append SimplexNodeWrapper nodes
            menu = EditorUtils.GetTypeSelectionMenu(typeof(SimplexNode), SelectedSimplexNode, menu);


            //Append Reflection
            foreach (var type in UserTypePrefs.GetPreferedTypesList(typeof(object)))
            {
                var icon    = type.IsSubclassOf(typeof(UnityEngine.Object))? UnityEditor.EditorGUIUtility.ObjectContent(null, type).image : null;
                var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).ToList();
                methods.AddRange(type.GetExtensionMethods());
                foreach (var m in methods.OrderBy(m => !m.IsStatic).OrderBy(m => m.IsSpecialName).OrderBy(m => m.DeclaringType != type))
                {
                    if (m.IsGenericMethod)
                    {
                        continue;
                    }

                    if (m.IsObsolete())
                    {
                        continue;
                    }

                    var categoryName = "Functions/Reflected/" + type.FriendlyName() + "/" + (m.IsSpecialName? "Properties/" : "Methods/");
                    if (m.DeclaringType != type)
                    {
                        categoryName += "More/";
                    }
                    var name = categoryName + m.SignatureName();
                    menu.AddItem(new GUIContent(name, icon, null), false, SelectedMethod, m);
                }

/*
 *                              foreach (var f in type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public)){
 *                                      if (f.IsReadOnly()){
 *                                              var categoryName = "Functions/Reflected/" + type.FriendlyName() + "/Constants/";
 *                                              if (f.DeclaringType != type){ categoryName += "More/"; }
 *                                              var name = categoryName + f.Name;
 *                                              menu.AddItem(new GUIContent(name, icon, null), false, SelectedFieldGet, f);
 *                                      }
 *                              }
 */
            }


            //Append Variables both local and global
            var variables = new Dictionary <IBlackboard, List <Variable> >();

            if (blackboard != null)
            {
                variables[blackboard] = blackboard.variables.Values.ToList();
            }
            foreach (var globalBB in GlobalBlackboard.allGlobals)
            {
                variables[globalBB] = globalBB.variables.Values.ToList();
            }

            foreach (var pair in variables)
            {
                foreach (var _bbVar in pair.Value)
                {
                    var bbVar     = _bbVar;
                    var finalName = pair.Key == blackboard? bbVar.name : string.Format("{0}/{1}", pair.Key.name, bbVar.name);
                    menu.AddItem(new GUIContent("Variables/Get Blackboard Variable/Get " + finalName, null, "Get Blackboard Variable"), false, () => {
                        var genericType = typeof(GetVariable <>).MakeGenericType(new System.Type[] { bbVar.varType });
                        var varNode     = (VariableNode)AddNode(genericType, mousePos);
                        genericType.GetMethod("SetTargetVariableName").Invoke(varNode, new object[] { finalName });
                    });
                    menu.AddItem(new GUIContent("Variables/Set Blackboard Variable/Set " + finalName, null, "Set Blackboard Variable"), false, () => {
                        var genericType = typeof(SetVariable <>).MakeGenericType(new System.Type[] { bbVar.varType });
                        var varNode     = (FlowNode)AddNode(genericType, mousePos);
                        genericType.GetMethod("SetTargetVariableName").Invoke(varNode, new object[] { finalName });
                    });
                }
            }


            //Append Project found Macros
            var projectMacroGUIDS = UnityEditor.AssetDatabase.FindAssets("t:Macro");

            foreach (var guid in projectMacroGUIDS)
            {
                var path  = UnityEditor.AssetDatabase.GUIDToAssetPath(guid);
                var macro = (Macro)UnityEditor.AssetDatabase.LoadAssetAtPath(path, typeof(Macro));
                if (macro != this)
                {
                    menu.AddItem(new GUIContent("MACROS/" + macro.name, null, macro.graphComments), false, SelectedMacro, macro);
                }
            }

            //Append Create new Macro
            menu.AddItem(new GUIContent("MACROS/Create New...", null, "Create a new macro"), false, () =>
            {
                var newMacro = EditorUtils.CreateAsset <Macro>(true);
                if (newMacro != null)
                {
                    var wrapper   = AddNode <MacroNodeWrapper>(mousePos);
                    wrapper.macro = newMacro;
                }
            });

            return(menu);
        }
コード例 #18
0
    public static void SetupInput(List <Type> setType)
    {
        eventHandlers  = new List <KeyValuePair <EventHandlerAttribute, Delegate> >();
        hotkeyHandlers = new List <KeyValuePair <HotkeyAttribute, Delegate> >();
        contextEntries = new List <KeyValuePair <ContextEntryAttribute, MenuFunctionData> >();

        IEnumerable <Assembly> scriptAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where((Assembly assembly) => assembly.FullName.Contains("Assembly"));

        foreach (Assembly assembly in scriptAssemblies)
        {
            foreach (Type type in assembly.GetTypes())
            {
                bool getType = false;
                foreach (var t in setType)
                {
                    if (type == t || type == typeof(EditorState))
                    {
                        getType = true;
                        break;
                    }
                }

                if (!getType)
                {
                    continue;
                }

                foreach (MethodInfo method in type.GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static))
                {
                    Delegate actionDelegate = null;
                    foreach (object attr in method.GetCustomAttributes(true))
                    {
                        Type attrType = attr.GetType();
                        if (attrType == typeof(EventHandlerAttribute))
                        {
                            if (EventHandlerAttribute.AssureValidity(method, attr as EventHandlerAttribute))
                            {
                                if (actionDelegate == null)
                                {
                                    actionDelegate = Delegate.CreateDelegate(typeof(Action <EditorInputInfo>), method);
                                }

                                eventHandlers.Add(new KeyValuePair <EventHandlerAttribute, Delegate>(attr as EventHandlerAttribute, actionDelegate));
                            }
                        }
                        else if (attrType == typeof(HotkeyAttribute))
                        {
                            if (HotkeyAttribute.AssureValidity(method, attr as HotkeyAttribute))
                            {
                                if (actionDelegate == null)
                                {
                                    actionDelegate = Delegate.CreateDelegate(typeof(Action <EditorInputInfo>), method);
                                }
                                hotkeyHandlers.Add(new KeyValuePair <HotkeyAttribute, Delegate>(attr as HotkeyAttribute, actionDelegate));
                            }
                        }
                        else if (attrType == typeof(ContextEntryAttribute))
                        {
                            if (ContextEntryAttribute.AssureValidity(method, attr as ContextEntryAttribute))
                            {
                                if (actionDelegate == null)
                                {
                                    actionDelegate = Delegate.CreateDelegate(typeof(Action <EditorInputInfo>), method);
                                }

                                MenuFunctionData menuFunction = (object callbackObj) =>
                                {
                                    if (!(callbackObj is EditorInputInfo))
                                    {
                                        throw new UnityException("Callback Object passed by context is not of type EditorMenuCallback!");
                                    }
                                    actionDelegate.DynamicInvoke(callbackObj as EditorInputInfo);
                                };
                                contextEntries.Add(new KeyValuePair <ContextEntryAttribute, MenuFunctionData>(attr as ContextEntryAttribute, menuFunction));
                            }
                        }
                    }
                }
            }
        }

        eventHandlers.Sort((handlerA, handlerB) => handlerA.Key.priority.CompareTo(handlerB.Key.priority));
        hotkeyHandlers.Sort((handlerA, handlerB) => handlerA.Key.priority.CompareTo(handlerB.Key.priority));
    }
コード例 #19
0
 public void Setup(string setLabel, OnActivateItemWithParameter setEffect, object setEffectParameterValue)
 {
     label = GUIContentPool.Create(setLabel);
     effectWithParameter  = setEffect;
     effectParameterValue = setEffectParameterValue;
 }
コード例 #20
0
        ////////////////////////////////////////
        ///////////GUI AND EDITOR STUFF/////////
        ////////////////////////////////////////
                #if UNITY_EDITOR
        protected override void OnTaskInspectorGUI()
        {
            if (!Application.isPlaying && GUILayout.Button("Select Static Method"))
            {
                UnityEditor.GenericMenu.MenuFunction2 MethodSelected = (m) => {
                    functionWrapper = ReflectedWrapper.Create((MethodInfo)m, blackboard);
                };

                var menu = new UnityEditor.GenericMenu();
                foreach (var t in UserTypePrefs.GetPreferedTypesList(typeof(object), true))
                {
                    foreach (var m in t.GetMethods(BindingFlags.Static | BindingFlags.Public).OrderBy(m => !m.IsSpecialName))
                    {
                        if (m.IsGenericMethod)
                        {
                            continue;
                        }

                        var parameters = m.GetParameters();
                        if (parameters.Length > 3)
                        {
                            continue;
                        }

                        menu.AddItem(new GUIContent(t.FriendlyName() + "/" + m.SignatureName()), false, MethodSelected, m);
                    }
                }
                menu.ShowAsContext();
                Event.current.Use();
            }


            if (targetMethod != null)
            {
                GUILayout.BeginVertical("box");
                UnityEditor.EditorGUILayout.LabelField("Type", targetMethod.DeclaringType.FriendlyName());
                UnityEditor.EditorGUILayout.LabelField("Method", targetMethod.Name);
                UnityEditor.EditorGUILayout.LabelField("Returns", targetMethod.ReturnType.FriendlyName());

                if (targetMethod.ReturnType == typeof(IEnumerator))
                {
                    GUILayout.Label("<b>This will execute as a Coroutine</b>");
                }

                GUILayout.EndVertical();

                var paramNames = targetMethod.GetParameters().Select(p => p.Name.SplitCamelCase()).ToArray();
                var variables  = functionWrapper.GetVariables();
                if (targetMethod.ReturnType == typeof(void))
                {
                    for (var i = 0; i < paramNames.Length; i++)
                    {
                        EditorUtils.BBParameterField(paramNames[i], variables[i]);
                    }
                }
                else
                {
                    for (var i = 0; i < paramNames.Length; i++)
                    {
                        EditorUtils.BBParameterField(paramNames[i], variables[i + 1]);
                    }
                    EditorUtils.BBParameterField("Save Return Value", variables[0], true);
                }
            }
        }
コード例 #21
0
        /// <summary>
        /// Fetches all event handlers
        /// </summary>
        public static void SetupInput()
        {
            eventHandlers  = new List <KeyValuePair <EventHandlerAttribute, Delegate> >();
            hotkeyHandlers = new List <KeyValuePair <HotkeyAttribute, Delegate> >();
            contextEntries = new List <KeyValuePair <ContextEntryAttribute, MenuFunctionData> >();
            contextFillers = new List <KeyValuePair <ContextFillerAttribute, Delegate> >();

            // Iterate through each static method

            Assembly assembly = Assembly.GetAssembly(typeof(NodeEditorInputSystem));

            foreach (Type type in assembly.GetTypes())
            {
                foreach (MethodInfo method in type.GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic |
                                                              BindingFlags.Static))
                {
                    #region Event-Attributes recognition and storing

                    // Check the method's attributes for input handler definitions
                    Delegate actionDelegate = null;
                    foreach (object attr in method.GetCustomAttributes(true))
                    {
                        Type attrType = attr.GetType();
                        if (attrType == typeof(EventHandlerAttribute))
                        {
                            // Method is an eventHandler
                            if (EventHandlerAttribute.AssureValidity(method, attr as EventHandlerAttribute))
                            {
                                // Method signature is correct, so we register this handler
                                if (actionDelegate == null)
                                {
                                    actionDelegate = Delegate.CreateDelegate(typeof(Action <NodeEditorInputInfo>), method);
                                }
                                eventHandlers.Add(new KeyValuePair <EventHandlerAttribute, Delegate>(attr as EventHandlerAttribute, actionDelegate));
                            }
                        }
                        else if (attrType == typeof(HotkeyAttribute))
                        {
                            // Method is an hotkeyHandler
                            if (HotkeyAttribute.AssureValidity(method, attr as HotkeyAttribute))
                            {
                                // Method signature is correct, so we register this handler
                                if (actionDelegate == null)
                                {
                                    actionDelegate = Delegate.CreateDelegate(typeof(Action <NodeEditorInputInfo>), method);
                                }
                                hotkeyHandlers.Add(new KeyValuePair <HotkeyAttribute, Delegate>(attr as HotkeyAttribute, actionDelegate));
                            }
                        }
                        else if (attrType == typeof(ContextEntryAttribute))
                        {
                            // Method is an contextEntry
                            if (ContextEntryAttribute.AssureValidity(method, attr as ContextEntryAttribute))
                            {
                                // Method signature is correct, so we register this handler
                                if (actionDelegate == null)
                                {
                                    actionDelegate = Delegate.CreateDelegate(typeof(Action <NodeEditorInputInfo>), method);
                                }
                                // Create a proper MenuFunction as a wrapper for the delegate that converts the object to NodeEditorInputInfo
                                MenuFunctionData menuFunction = (object callbackObj) =>
                                {
                                    if (!(callbackObj is NodeEditorInputInfo))
                                    {
                                        throw new UnityException("Callback Object passed by context is not of type NodeEditorMenuCallback!");
                                    }
                                    actionDelegate.DynamicInvoke(callbackObj as NodeEditorInputInfo);
                                };
                                contextEntries.Add(
                                    new KeyValuePair <ContextEntryAttribute, MenuFunctionData>(attr as ContextEntryAttribute, menuFunction));
                            }
                        }
                        else if (attrType == typeof(ContextFillerAttribute))
                        {
                            // Method is an contextFiller
                            if (ContextFillerAttribute.AssureValidity(method, attr as ContextFillerAttribute))
                            {
                                // Method signature is correct, so we register this handler
                                Delegate methodDel = Delegate.CreateDelegate(typeof(Action <NodeEditorInputInfo, GenericMenu>), method);
                                contextFillers.Add(new KeyValuePair <ContextFillerAttribute, Delegate>(attr as ContextFillerAttribute, methodDel));
                            }
                        }
                    }

                    #endregion
                }
            }

            eventHandlers.Sort((handlerA, handlerB) => handlerA.Key.priority.CompareTo(handlerB.Key.priority));
            hotkeyHandlers.Sort((handlerA, handlerB) => handlerA.Key.priority.CompareTo(handlerB.Key.priority));
        }
コード例 #22
0
        ////////////////////////////////////////
        ///////////GUI AND EDITOR STUFF/////////
        ////////////////////////////////////////
                #if UNITY_EDITOR
        protected override void OnTaskInspectorGUI()
        {
            if (!Application.isPlaying && GUILayout.Button("Select Static Method"))
            {
                UnityEditor.GenericMenu.MenuFunction2 MethodSelected = (m) => {
                    var newMethod = (MethodInfo)m;
                    this.method = new SerializedMethodInfo(newMethod);
                    this.parameters.Clear();
                    foreach (var p in newMethod.GetParameters())
                    {
                        var newParam = new BBObjectParameter {
                            bb = blackboard
                        };
                        newParam.SetType(p.ParameterType);
                        if (p.IsOptional)
                        {
                            newParam.value = p.DefaultValue;
                        }
                        parameters.Add(newParam);
                    }

                    if (newMethod.ReturnType != typeof(void))
                    {
                        this.returnValue = new BBObjectParameter {
                            bb = blackboard
                        };
                        this.returnValue.SetType(newMethod.ReturnType);
                    }
                };

                var menu = new UnityEditor.GenericMenu();
                foreach (var t in UserTypePrefs.GetPreferedTypesList(typeof(object), true))
                {
                    foreach (var m in t.GetMethods(BindingFlags.Static | BindingFlags.Public).OrderBy(m => !m.IsSpecialName))
                    {
                        if (m.IsGenericMethod)
                        {
                            continue;
                        }

                        var parameters = m.GetParameters();
                        if (parameters.Length > 3)
                        {
                            continue;
                        }

                        menu.AddItem(new GUIContent(t.FriendlyName() + "/" + m.SignatureName()), false, MethodSelected, m);
                    }
                }
                menu.ShowAsContext();
                Event.current.Use();
            }


            if (targetMethod != null)
            {
                GUILayout.BeginVertical("box");
                UnityEditor.EditorGUILayout.LabelField("Type", targetMethod.DeclaringType.FriendlyName());
                UnityEditor.EditorGUILayout.LabelField("Method", targetMethod.Name);
                UnityEditor.EditorGUILayout.LabelField("Returns", targetMethod.ReturnType.FriendlyName());
                GUILayout.EndVertical();

                var paramNames = targetMethod.GetParameters().Select(p => p.Name.SplitCamelCase()).ToArray();
                for (var i = 0; i < paramNames.Length; i++)
                {
                    EditorUtils.BBParameterField(paramNames[i], parameters[i]);
                }

                if (targetMethod.ReturnType != typeof(void))
                {
                    EditorUtils.BBParameterField("Save Return Value", returnValue, true);
                }
            }
        }