public void OnContextClick(int itemIndex) { GenericMenu genericMenu = new GenericMenu(); genericMenu.AddItem(new GUIContent("Unexpose"), false, (GenericMenu.MenuFunction2) (data => this.Delete((int) data)), (object) itemIndex); genericMenu.AddItem(new GUIContent("Rename"), false, (GenericMenu.MenuFunction2) (data => this.m_ReorderableListWithRenameAndScrollView.BeginRename((int) data, 0.0f)), (object) itemIndex); genericMenu.ShowAsContext(); }
/// <summary> /// Callback to add a new node. /// </summary> private void OnAddNode(ReorderableList list) { // Get all node scripts var nodeTypes = new List <System.Type>(); foreach (System.Type type in BehaviourTreeUtility.GetNodeTypes()) { if (!type.IsSubclassOf(typeof(BranchNode))) { nodeTypes.Add(type); } } // Create the menu var menu = new UnityEditor.GenericMenu(); // Add node types to the menu for (int i = 0; i < nodeTypes.Count; i++) { var nodeType = nodeTypes[i]; var nodeInfo = AttributeUtility.GetAttribute <NodeInfoAttribute>(nodeType, false) ?? new NodeInfoAttribute(); menu.AddItem(new GUIContent(nodeInfo.category + nodeType.Name), false, delegate() { ActionStateUtility.AddNode(m_ActionState, nodeType); RegisterEditorOnGUI(); }); } // Show the context menu menu.ShowAsContext(); }
private void SelectBehaviorBrain() { GUIContent content = new GUIContent(BehaviorTreeEditor.active != null ? BehaviorTreeEditor.active.name : "[None Selected]"); float width = EditorStyles.toolbarDropDown.CalcSize(content).x; width = Mathf.Clamp(width, 100f, width); if (GUILayout.Button(content, EditorStyles.toolbarDropDown, GUILayout.Width(width))) { GenericMenu menu = new GenericMenu(); if (BehaviorTreeEditor.active != null) SelectBehaviorBrainMenu(BehaviorTreeEditor.active, ref menu); menu.AddItem(new GUIContent("[Craete New]"), false, delegate () { BehaviorTree bt = AssetCreator.CreateAsset<BehaviorTree>(true); if (bt != null) { bt.Name = bt.name; Root root = BehaviorTreeEditorUtility.AddNode<Root>(BehaviorTreeEditor.center, bt); bt.rootNode = root; root.Name = "Root"; AssetDatabase.SaveAssets(); BehaviorTreeEditor.SelectBehaviorTrees(bt); } }); menu.ShowAsContext(); } }
//yeah this is very special but.... public static void ShowConfiguredTypeSelectionMenu(Type type, Action <Type> callback, bool showInterfaces = true) { GenericMenu.MenuFunction2 Selected = delegate(object t){ callback((Type)t); }; var menu = new UnityEditor.GenericMenu(); foreach (System.Type t in NCPrefs.GetCommonlyUsedTypes(typeof(object))) { if (type.IsAssignableFrom(t) || (t.IsInterface && showInterfaces)) { var category = "Classes/"; if (t.IsInterface) { category = "Interfaces/"; } if (t.IsEnum) { category = "Enumerations/"; } var nsString = string.IsNullOrEmpty(t.Namespace)? "No Namespace/" : (t.Namespace.Replace(".", "/") + "/"); menu.AddItem(new GUIContent(category + nsString + TypeName(t)), false, Selected, t); } } menu.AddDisabledItem(new GUIContent("Add more in Type Configurator")); menu.ShowAsContext(); Event.current.Use(); }
internal static void Show(int savedFilterInstanceID) { GUIContent content = new GUIContent("Delete"); GenericMenu genericMenu = new GenericMenu(); genericMenu.AddItem(content, false, new GenericMenu.MenuFunction(new ProjectBrowser.SavedFiltersContextMenu(savedFilterInstanceID).Delete)); genericMenu.ShowAsContext(); }
protected override void OnRightClick(Vector2 mousePosition) { base.OnRightClick(mousePosition); GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Add Sequence Action"), false, OnAddNode, mousePosition); menu.ShowAsContext(); }
protected override void OnRightClick(Vector2 mousePosition) { base.OnRightClick(mousePosition); GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Delete State Transition"), false, Delete); menu.ShowAsContext(); }
/// <summary> /// Shows a context menu to add a new parent. /// </summary> void OnContextMenu() { var menu = new UnityEditor.GenericMenu(); // Get the active game object var gameObject = Selection.activeGameObject; // The selected game object is not null? if (gameObject != null) { // Gets all scripts that inherits from ParentBehaviour class MonoScript[] scripts = FileUtility.GetScripts <ParentBehaviour>(); for (int i = 0; i < scripts.Length; i++) { var type = scripts[i].GetClass(); // Get the component path string componentPath = "Add Parent/"; AddComponentMenu componentMenu = AttributeUtility.GetAttribute <AddComponentMenu>(type, false); if (componentMenu == null || componentMenu.componentMenu != string.Empty) { componentMenu = AttributeUtility.GetAttribute <AddComponentMenu>(type, true); if (componentMenu != null && componentMenu.componentMenu != string.Empty) { componentPath += componentMenu.componentMenu; } else { componentPath += type.ToString().Replace('.', '/'); } // Add to menu menu.AddItem(new GUIContent(componentPath), false, delegate() { BehaviourWindow.activeParent = StateUtility.AddState(gameObject, type) as ParentBehaviour; }); } } } else { menu.AddDisabledItem(new GUIContent("Add Parent/")); ShowNotification(new GUIContent("Select a Game Object and right click in this window!")); } // Add option to paste states if (Selection.activeGameObject != null && StateUtility.statesToPaste != null && StateUtility.statesToPaste.Length > 0) { menu.AddItem(new GUIContent("Paste State"), false, delegate() { StateUtility.CloneStates(Selection.activeGameObject, StateUtility.statesToPaste, null); }); } else { menu.AddDisabledItem(new GUIContent("Paste State")); } // Refresh window? // menu.AddSeparator(""); // menu.AddItem(new GUIContent("Refresh"), false ,Refresh); // Shows the controller menu menu.ShowAsContext(); }
private void OnTransitionContextClick(int index){ GenericMenu menu = new GenericMenu (); menu.AddItem (new GUIContent("Remove"),false,delegate() { FsmEditorUtility.DestroyImmediate(node.Transitions[index]); node.Transitions = ArrayUtility.Remove (node.Transitions, transitions [index]); this.ResetTransitionList(); }); menu.ShowAsContext (); }
public static void Show(int itemIndex, FlexibleMenu caller) { FlexibleMenu.ItemContextMenu.s_Caller = caller; GenericMenu genericMenu = new GenericMenu(); genericMenu.AddItem(new GUIContent("Edit..."), false, new GenericMenu.MenuFunction2(FlexibleMenu.ItemContextMenu.Edit), itemIndex); genericMenu.AddItem(new GUIContent("Delete"), false, new GenericMenu.MenuFunction2(FlexibleMenu.ItemContextMenu.Delete), itemIndex); genericMenu.ShowAsContext(); GUIUtility.ExitGUI(); }
public void OnTreeViewContextClick(int index) { AudioMixerItem node = (AudioMixerItem) this.m_TreeView.FindNode(index); if (node == null) return; GenericMenu genericMenu = new GenericMenu(); genericMenu.AddItem(new GUIContent("Delete AudioMixer"), false, new GenericMenu.MenuFunction2(this.DeleteAudioMixerCallback), (object) node.mixer); genericMenu.ShowAsContext(); }
public void OnTreeViewContextClick(int index) { AudioMixerItem audioMixerItem = (AudioMixerItem)this.m_TreeView.FindNode(index); if (audioMixerItem != null) { GenericMenu genericMenu = new GenericMenu(); genericMenu.AddItem(new GUIContent("Delete AudioMixer"), false, new GenericMenu.MenuFunction2(this.DeleteAudioMixerCallback), audioMixerItem.mixer); genericMenu.ShowAsContext(); } }
/// <summary> /// Draws the gui control. /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty to make the custom GUI for.</param> /// <param name="label">The label of this property.</param> /// </summary> public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) { // Get state var targetState = property.serializedObject.targetObject as InternalStateBehaviour; // It's a valid state? if (targetState != null) { // Draw prefix label #if UNITY_4_0_0 || UNITY_4_1 || UNITY_4_2 Rect controlPosition = EditorGUI.PrefixLabel(position, EditorGUIUtility.GetControlID(FocusType.Passive, position), label); #else Rect controlPosition = EditorGUI.PrefixLabel(position, label); #endif // Get the parent ParentBehaviour parent = targetState.parent; // Draw button as popup if (GUI.Button(controlPosition, parent != null ? parent.stateName : "Null", EditorStyles.popup)) { // Get valid parents for the state List<ParentBehaviour> validParents = new List<ParentBehaviour>(); var targetParent = targetState as ParentBehaviour; validParents.AddRange(targetState.GetComponents<ParentBehaviour>()); // The target state is a parent behaviour? if (targetParent != null) { for (int i = validParents.Count - 1; i >= 0; i--) { // it's the targetParent? if (validParents[i] == targetParent) validParents.RemoveAt(i); // The parent is a child of the target parent? else if (validParents[i].IsAncestor(targetParent)) validParents.RemoveAt(i); } } // Create menu var menu = new GenericMenu(); // Add null item menu.AddItem(new GUIContent("Null"), parent == null, this.OnSetNewParent, new SetParent(targetState, null)); // Add menu items var parentNames = new List<string>(); for (int i = 0; i < validParents.Count; i++) { string parentName = StringHelper.GetUniqueNameInList(parentNames, validParents[i].fullStateName); parentNames.Add(parentName); menu.AddItem(new GUIContent(parentName), parent == validParents[i], this.OnSetNewParent, new SetParent(targetState, validParents[i])); } // Show context menu menu.ShowAsContext(); } } }
private void DrawLocationMenu() { if (GUILayout.Button("Menu", "MiniPullDown", GUILayout.Width(56))) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("New Location"), false, AddNewLocation); menu.AddItem(new GUIContent("Sort/By Name"), false, SortLocationsByName); menu.AddItem(new GUIContent("Sort/By ID"), false, SortLocationsByID); menu.AddItem(new GUIContent("Sync From DB"), database.syncInfo.syncLocations, ToggleSyncLocationsFromDB); menu.ShowAsContext(); } }
private void DrawToolbarGUI() { Rect rect = new Rect(0, 0, Screen.width, 50f); //rect.height = 50f; GUILayout.BeginArea(rect, MapEditor.toolbar); GUILayout.BeginHorizontal(); //float curToolbarWidth = 0; //if (isEditorMap) { if (GUILayout.Button("File", MapEditor.toolbarDropdown, GUILayout.Width(50))) { GenericMenu menu = new UnityEditor.GenericMenu(); //menu.AddSeparator(""); menu.AddItem(new GUIContent("LoadTex"), false, () => { MapEditor.BgTexture = EditorTool.LoadTexture(); }); //menu.DropDown(new Rect(0, 0, 20, 30)); menu.ShowAsContext(); } if (GUILayout.Button("工具", MapEditor.toolbarDropdown, GUILayout.Width(75))) { GenericMenu menu = new UnityEditor.GenericMenu(); //menu.AddSeparator(""); menu.AddItem(new GUIContent("鼠标"), false, () => { this.SetState(0); }); menu.AddItem(new GUIContent("笔刷"), false, () => { this.SetState(1); }); menu.AddItem(new GUIContent("移动"), false, () => { this.SetState(2); }); //menu.DropDown(new Rect(0, 0, 20, 30)); menu.ShowAsContext(); } string state = GetToolName();//new GUIContent(state, "当前编辑状态") GUILayout.Label("当前编辑状态:" + state, GUILayout.Width(200)); } if ((Pagetype == PageType.Editor || Pagetype == PageType.EditorSub) && EditorType == ToolType.Brush) { if (GUILayout.Button("选择格子类型", MapEditor.toolbarDropdown, GUILayout.Width(100))) { GenericMenu menu = new UnityEditor.GenericMenu(); //menu.AddSeparator(""); menu.AddItem(new GUIContent("不可见"), false, () => { this.SetCellType(0); }); menu.AddItem(new GUIContent("阻挡"), false, () => { this.SetCellType(1); }); menu.AddItem(new GUIContent("可编辑"), false, () => { this.SetCellType(2); }); //menu.DropDown(new Rect(0, 0, 20, 30)); menu.ShowAsContext(); } string state = GetCellName();//new GUIContent(state, "当前编辑状态") GUILayout.Label("选定格子:" + state); } GUILayout.EndHorizontal(); GUILayout.EndArea(); }
private void DrawTemplateMenu() { if (GUILayout.Button("Menu", "MiniPullDown", GUILayout.Width(56))) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Export XML..."), false, ExportTemplate); menu.AddItem(new GUIContent("Import XML..."), false, ImportTemplate); menu.AddItem(new GUIContent("Update From Assets"), false, ConfirmUpdateFromAssets); menu.AddItem(new GUIContent("Reset"), false, ResetTemplate); menu.ShowAsContext(); } }
private void DrawNodeEditorMenu() { if (GUILayout.Button("Menu", "MiniPullDown", GUILayout.Width(56))) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("New Conversation"), false, AddNewConversationToNodeEditor); menu.AddItem(new GUIContent("Sort/By Title"), false, SortConversationsByTitle); menu.AddItem(new GUIContent("Sort/By ID"), false, SortConversationsByID); menu.AddItem(new GUIContent("Actor Names"), showActorNames, ToggleShowActorNames); menu.AddItem(new GUIContent("Outline Mode"), false, ActivateOutlineMode); menu.ShowAsContext(); } }
/// <summary> /// Show the "Add Track Group" context menu. /// </summary> /// <param name="cutscene">The current Cutscene that the track group will be added to.</param> public static void ShowAddTrackGroupContextMenu(Cutscene cutscene) { GenericMenu createMenu = new GenericMenu(); foreach (Type type in DirectorHelper.GetAllSubTypes(typeof(TrackGroup))) { TrackGroupContextData userData = getContextDataFromType(cutscene, type); string text = string.Format(userData.Label); createMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction2(AddTrackGroup), userData); } createMenu.ShowAsContext(); }
internal static void Show(SerializedProperty prop) { GUIContent content1 = new GUIContent("Copy"); GUIContent content2 = new GUIContent("Paste"); GenericMenu genericMenu = new GenericMenu(); genericMenu.AddItem(content1, false, new GenericMenu.MenuFunction(new GradientContextMenu(prop).Copy)); if (ParticleSystemClipboard.HasSingleGradient()) genericMenu.AddItem(content2, false, new GenericMenu.MenuFunction(new GradientContextMenu(prop).Paste)); else genericMenu.AddDisabledItem(content2); genericMenu.ShowAsContext(); }
public static void DrawModuleSettingsGUI(IWindowFlowAddon addon, string caption, GenericMenu settingsMenu, System.Action onGUI) { CustomGUI.Splitter(new Color(0.7f, 0.7f, 0.7f, 0.2f)); GUILayout.BeginHorizontal(); { GUILayout.Label(caption.ToSentenceCase().UppercaseWords(), EditorStyles.boldLabel); if (settingsMenu != null) { var settingsStyle = new GUIStyle("PaneOptions"); if (GUILayout.Button(string.Empty, settingsStyle) == true) { settingsMenu.ShowAsContext(); } } } GUILayout.EndHorizontal(); CustomGUI.Splitter(new Color(0.7f, 0.7f, 0.7f, 0.2f)); GUILayout.BeginVertical(FlowSystemEditorWindow.defaultSkin.box); { if (addon != null && addon.InstallationNeeded() == true) { GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); if (GUILayoutExt.LargeButton("Install", 40f, 200f) == true) { addon.Install(); } GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); } else { onGUI(); } } GUILayout.EndVertical(); }
private void SelectGameObject(){ if (GUILayout.Button(FsmEditor.ActiveGameObject != null?FsmEditor.ActiveGameObject.name:"[None Selected]", EditorStyles.toolbarDropDown,GUILayout.Width(100))) { GenericMenu toolsMenu = new GenericMenu(); List<ICodeBehaviour> behaviours=FsmEditorUtility.FindInScene<ICodeBehaviour>(); foreach(ICodeBehaviour behaviour in behaviours){ GameObject mGameObject=behaviour.gameObject; toolsMenu.AddItem( new GUIContent(behaviour.name),false, delegate() { FsmEditor.SelectGameObject(mGameObject); }); } toolsMenu.ShowAsContext(); } }
public override void NodeUI(UnityEditor.Graphs.GraphGUI host) { base.graphGUI = host as UnityEditor.Graphs.AnimationStateMachine.GraphGUI; Assert.NotNull(base.graphGUI); Event current = Event.current; if (UnityEditor.Graphs.AnimationStateMachine.Node.IsRightClick()) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Make Transition"), false, new GenericMenu.MenuFunction(this.MakeTransitionCallback)); menu.ShowAsContext(); current.Use(); } }
public void OnContextClick(int itemIndex) { GenericMenu genericMenu = new GenericMenu(); genericMenu.AddItem(new GUIContent("Unexpose"), false, delegate(object data) { this.Delete((int)data); }, itemIndex); genericMenu.AddItem(new GUIContent("Rename"), false, delegate(object data) { this.m_ReorderableListWithRenameAndScrollView.BeginRename((int)data, 0f); }, itemIndex); genericMenu.ShowAsContext(); }
public static void OpenContextMenu(IEnumerable<ContextMenuItem> items) { GenericMenu contextMenu = new GenericMenu(); foreach (var item in items) { var handler = item.Handler; contextMenu.AddOptionalItem( item.IsEnabled, new GUIContent(item.Caption), item.IsChecked, () => handler()); } contextMenu.ShowAsContext(); }
private void OpenGroupContextMenu(AudioMixerTreeViewNode audioNode, bool visible) { GenericMenu genericMenu = new GenericMenu(); if (this.NodeWasToggled != null) { genericMenu.AddItem(new GUIContent((!visible) ? "Show Group" : "Hide group"), false, delegate { this.NodeWasToggled(audioNode, !visible); }); } genericMenu.AddSeparator(string.Empty); AudioMixerColorCodes.AddColorItemsToGenericMenu(genericMenu, audioNode.group); genericMenu.ShowAsContext(); }
protected override void OnSPInspectorGUI() { this.serializedObject.Update(); this.DrawPropertyField(EditorHelper.PROP_SCRIPT); _toAdd.Clear(); _toAdd.AddRange(System.Enum.GetValues(typeof(EventTriggerType)).Cast<EventTriggerType>()); var triggersProp = this.serializedObject.FindProperty(PROP_TRIGGERS); for (int i = 0; i < triggersProp.arraySize; i++) { var prop = triggersProp.GetArrayElementAtIndex(i); var eventId = prop.FindPropertyRelative(PROP_EVENTID).GetEnumValue<EventTriggerType>(); var label = EditorHelper.TempContent(eventId.ToString()); var h = _drawer.GetPropertyHeight(prop, label); var rect = EditorGUILayout.GetControlRect(true, h); _drawer.OnGUI(rect, prop, label); _toAdd.Remove(eventId); } var btnHeight = EditorGUIUtility.singleLineHeight * 1.5f; var btnVerPadding = EditorGUIUtility.singleLineHeight / 2f; var btnRect = EditorGUILayout.GetControlRect(false, btnVerPadding + btnVerPadding + btnHeight); var btnWidth = Mathf.Min(btnRect.width, 200f); var btnHorPadding = Mathf.Max(0f, (btnRect.width - btnWidth) / 2f); btnRect = new Rect(btnRect.xMin + btnHorPadding, btnRect.yMin + btnVerPadding, btnWidth, btnHeight); if(GUI.Button(btnRect, "Add New Event Type")) { var labels = (from e in _toAdd select e.ToString()).ToArray(); var menu = new GenericMenu(); foreach(var e in _toAdd) { menu.AddItem(EditorHelper.TempContent(e.ToString()), false, () => { triggersProp.arraySize++; var el = triggersProp.GetArrayElementAtIndex(triggersProp.arraySize - 1); el.FindPropertyRelative(PROP_EVENTID).SetEnumValue(e); el.FindPropertyRelative(TriggerPropertyDrawer.PROP_TARGETS).arraySize = 0; triggersProp.serializedObject.ApplyModifiedProperties(); }); } menu.ShowAsContext(); } this.DrawDefaultInspectorExcept(EditorHelper.PROP_SCRIPT, PROP_TRIGGERS); this.serializedObject.ApplyModifiedProperties(); }
void OnGUI(){ EditorGUILayout.HelpBox("Here you can specify frequently used types for your game for easier access wherever you need to select a type.\nFor example when you create a new blackboard variable or using any refelection based actions.", MessageType.Info); if (GUILayout.Button("Add New Type")){ GenericMenu.MenuFunction2 Selected = delegate(object t){ if (!typeList.Contains( (System.Type)t)){ typeList.Add( (System.Type)t); Save(); } else { ShowNotification(new GUIContent("Type already in list") ); } }; var menu = new UnityEditor.GenericMenu(); menu.AddItem(new GUIContent("Classes/System/Object"), false, Selected, typeof(object)); foreach(var t in EditorUtils.GetAssemblyTypes(typeof(object))){ var friendlyName = (string.IsNullOrEmpty(t.Namespace)? "No Namespace/" : t.Namespace.Replace(".", "/") + "/") + t.FriendlyName(); var category = "Classes/"; if (t.IsInterface) category = "Interfaces/"; if (t.IsEnum) category = "Enumerations/"; menu.AddItem(new GUIContent( category + friendlyName), false, Selected, t); } menu.ShowAsContext(); Event.current.Use(); } if (GUILayout.Button("RESET DEFAULTS")){ UserTypePrefs.ResetTypeConfiguration(); typeList = UserTypePrefs.GetPreferedTypesList(typeof(object), true); Save(); } scrollPos = GUILayout.BeginScrollView(scrollPos); for (int i = 0; i < typeList.Count; i++){ GUILayout.BeginHorizontal("box"); EditorGUILayout.LabelField(typeList[i].Name, typeList[i].Namespace); if (GUILayout.Button("X", GUILayout.Width(18))){ typeList.RemoveAt(i); Save(); } GUILayout.EndHorizontal(); } GUILayout.EndScrollView(); Repaint(); }
public static void DrawDraggableElementDeleteContextMenu(this ReorderableList lst, Rect area, int index, bool isActive, bool isFocused) { if (IsRightClickingDraggableArea(lst, area)) { Event.current.Use(); var menu = new GenericMenu(); menu.AddItem(new GUIContent("Delete"), false, () => { lst.serializedProperty.DeleteArrayElementAtIndex(index); lst.serializedProperty.serializedObject.ApplyModifiedProperties(); }); menu.ShowAsContext(); } }
public override void OnInspectorGUI() { base.OnInspectorGUI (); if (GUILayout.Button ("Add Validation")) { GenericMenu menu = new GenericMenu (); IEnumerable<Type> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()) .Where(type => typeof(IValidation<>).IsAssignableFrom(type) && type.IsClass && !type.IsAbstract); foreach (Type type in types) { Type mType=type; menu.AddItem(new GUIContent(mType.Name),false,delegate() { (target as MonoBehaviour).gameObject.AddComponent(mType); }); } menu.ShowAsContext (); } }
public static void ShowOutputSlotsMenu(GenericMenu.MenuFunction2 func, System.Type filterSlotDataType = null) { var mnu = new GenericMenu(); var generators = Component.FindObjectsOfType<CurvyGenerator>(); mnu.AddItem(new GUIContent("none"), false, func,null); foreach (var gen in generators) { var slots = findOutputSlots(gen, filterSlotDataType); foreach (CGModuleOutputSlot slot in slots) mnu.AddItem(new GUIContent(gen.name + "/" + slot.Module.ModuleName+"/"+slot.Info.Name), false, func, slot); } mnu.ShowAsContext(); }
private void SelectGameObject() { if (GUILayout.Button(BehaviorTreeEditor.activeGameObject != null ? BehaviorTreeEditor.activeGameObject.name : "[None Selected]", EditorStyles.toolbarDropDown, GUILayout.Width(100))) { GenericMenu toolsMenu = new GenericMenu(); List<Brain> brains = BehaviorTreeEditorUtility.FindInScene<Brain>(); foreach (Brain brain in brains) { GameObject gameObject = brain.gameObject; toolsMenu.AddItem(new GUIContent(gameObject.name), false, delegate () { BehaviorTreeEditor.SelectGameObject(gameObject); }); } toolsMenu.ShowAsContext(); } }
private void ShowAddPointerMenu <TItem>(string name, Action addItem, Action <TItem> addPointer) where TItem : IDiagramNodeItem { var ctxMenu = new UnityEditor.GenericMenu(); ctxMenu.AddItem(new GUIContent("New " + name), false, () => { InvertApplication.Execute(() => { addItem(); }); }); ctxMenu.AddSeparator(""); var nodeConfigSection = NodeViewModel.DiagramViewModel.CurrentRepository.AllOf <TItem>(); foreach (var item in nodeConfigSection) { var item1 = item; ctxMenu.AddItem(new GUIContent(item.Name), false, () => { InvertApplication.Execute(() => { addPointer(item1); }); }); } ctxMenu.ShowAsContext(); }
//public void DeletItem() //{ // items.Remove(item); //} private void OnGUI() { foreach (var item in items) { item.Draw(); item.PollEvents(); } Repaint(); switch (Event.current.type) { case EventType.MouseDown: if (Event.current.button == 1) { var gm = new UnityEditor.GenericMenu(); gm.AddItem(new GUIContent("Create Item Menu"), false, CreateItem); gm.ShowAsContext(); } break; } }
private void OnGUI() { foreach (var sb in StatButtons) { sb.Draw(); sb.PollEvents(); } Repaint(); switch (Event.current.type) { case EventType.MouseDown: if (Event.current.button == 1) { var gm = new UnityEditor.GenericMenu(); gm.AddItem(new GUIContent("Create Stat"), false, CreateButton); gm.AddItem(new GUIContent("Print Info"), false, () => { Debug.Log("Info Printed"); }); gm.ShowAsContext(); } break; } }
/// <summary> /// Shows a context menu for the supplied transition. /// <param name="transition">The target transition.</param> /// </summary> void ShowContextMenu(StateTransition transition) { var menu = new UnityEditor.GenericMenu(); var currentEventID = transition.eventID; // Add none menu.AddItem(new GUIContent("None"), currentEventID == 0, delegate() { StateUtility.SetNewEvent(m_State, transition, 0); this.Refresh(); }); // Add blackboard events var blackboard = m_State.blackboard; if (blackboard != null) { foreach (var fsmEvent in blackboard.fsmEvents) { int eventId = fsmEvent.id; menu.AddItem(new GUIContent(fsmEvent.name), currentEventID == fsmEvent.id, delegate() { StateUtility.SetNewEvent(m_State, transition, eventId); this.Refresh(); }); } } // Add GlobalBlackboard events // This is not The GlobalBlackboard? if (InternalGlobalBlackboard.Instance != null && blackboard != InternalGlobalBlackboard.Instance) { foreach (var globalEvent in InternalGlobalBlackboard.Instance.fsmEvents) { int eventId = globalEvent.id; var eventName = globalEvent.isSystem ? "System/" + globalEvent.name : "Global/" + globalEvent.name; menu.AddItem(new GUIContent(eventName), currentEventID == globalEvent.id, delegate() { StateUtility.SetNewEvent(m_State, transition, eventId); this.Refresh(); }); } } menu.AddSeparator(""); // Separator menu.AddItem(new GUIContent("Delete"), false, delegate() { StateUtility.RemoveTransition(m_State, transition); this.Refresh(); }); // Shows the context menu menu.ShowAsContext(); }
/// <summary> /// Show the node menu. /// <param name="node">The target node.</param> /// </summary> void NodeContextMenu(ActionNode node) { // Validate Paramenters if (node == null) { return; } // Create the menu var menu = new UnityEditor.GenericMenu(); // Copy/Cut/Paste/Duplicate menu.AddItem(new GUIContent("Copy"), false, delegate() { BehaviourTreeUtility.nodeToPaste = node; }); menu.AddItem(new GUIContent("Cut"), false, delegate() { BehaviourTreeUtility.nodeToPaste = node; OnDestroyNode(node); }); ActionNode[] nodesToPaste = ActionStateUtility.GetActionsAndConditions(BehaviourTreeUtility.nodeToPaste != null ? new ActionNode[] { BehaviourTreeUtility.nodeToPaste } : new ActionNode[0]); if (nodesToPaste.Length > 0) { menu.AddItem(new GUIContent("Paste"), false, delegate() { ActionStateUtility.PasteNodes(m_ActionState, nodesToPaste); }); } else { menu.AddDisabledItem(new GUIContent("Paste")); } menu.AddItem(new GUIContent("Duplicate"), false, delegate() { ActionStateUtility.PasteNodes(m_ActionState, new ActionNode[] { node }); }); // Separator menu.AddSeparator(""); // Delete menu.AddItem(new GUIContent("Delete"), false, delegate() { this.OnDestroyNode(node); }); // Show the context menu menu.ShowAsContext(); }
///---------------------------------------------------------------------------------------------- ///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(); } } }
protected void DrawToolbarGUI() { EditorGUILayout.BeginHorizontal("Toolbar"); GUI.backgroundColor = new Color(1f, 1f, 1f, 0.5f); if (GUILayout.Button("File", EditorStyles.toolbarDropDown, GUILayout.Width(50))) { var menu = new GenericMenu(); foreach (System.Collections.Generic.KeyValuePair <Type, NodeCanvasTypeData> data in NodeCanvasManager.CanvasTypes) { menu.AddItem(new GUIContent("New Canvas/" + data.Value.DisplayString), false, newCanvasTypeCallback, data.Value); } menu.AddSeparator(""); menu.AddItem(new GUIContent("Load Canvas", "Loads an Specified Empty CanvasType"), false, LoadCanvas); menu.AddSeparator(""); menu.AddItem(new GUIContent("Save Canvas"), false, SaveCanvas); menu.AddItem(new GUIContent("Save Canvas As"), false, SaveCanvasAs); menu.AddSeparator(""); // Load from canvas foreach (string sceneSave in NodeEditorSaveManager.GetSceneSaves()) { menu.AddItem(new GUIContent("Load Canvas from Scene/" + sceneSave), false, LoadSceneCanvasCallback, sceneSave); } // Save Canvas to Scene menu.AddItem(new GUIContent("Save Canvas to Scene"), false, () => { showModalPanel = true; Debug.Log(showModalPanel); }); menu.ShowAsContext(); } if (GUILayout.Button("Debug", EditorStyles.toolbarDropDown, GUILayout.Width(50))) { var menu = new GenericMenu(); // Toggles side panel menu.AddItem(new GUIContent("Sidebar"), showSideWindow, () => { showSideWindow = !showSideWindow; }); menu.ShowAsContext(); } GUILayout.Space(10); GUILayout.FlexibleSpace(); GUILayout.Label(new GUIContent("" + canvasCache.nodeCanvas.saveName + " (" + (canvasCache.nodeCanvas.livesInScene? "Scene Save" : "Asset Save") + ")", "Opened Canvas path: " + canvasCache.nodeCanvas.savePath), "ToolbarButton"); GUILayout.Label("Type: " + canvasCache.typeData.DisplayString + "/" + canvasCache.nodeCanvas.GetType().Name + "", "ToolbarButton"); GUI.backgroundColor = new Color(1, 0.3f, 0.3f, 1); if (GUILayout.Button("Force Re-init", EditorStyles.toolbarButton, GUILayout.Width(80))) { NodeEditor.ReInit(true); } EditorGUILayout.EndHorizontal(); GUI.backgroundColor = Color.white; }
void OnGUI() { EditorGUILayout.HelpBox("Here you can specify frequently used types for your game for easier access wherever you need to select a type\nFor example when setting the type of an Object variable as well as when setting the agent type in any 'Script Control' Task", MessageType.Info); if (GUILayout.Button("Add New Type")) { GenericMenu.MenuFunction2 Selected = delegate(object t){ if (!typeList.Contains((System.Type)t)) { typeList.Add((System.Type)t); Save(); } else { ShowNotification(new GUIContent("Type already in list")); } }; var menu = new UnityEditor.GenericMenu(); foreach (var t in EditorUtils.GetAssemblyTypes(typeof(object))) { var friendlyName = (string.IsNullOrEmpty(t.Namespace)? "No Namespace/" : t.Namespace.Replace(".", "/") + "/") + t.FriendlyName(); var category = "Classes/"; if (t.IsInterface) { category = "Interfaces/"; } if (t.IsEnum) { category = "Enumerations/"; } menu.AddItem(new GUIContent(category + friendlyName), false, Selected, t); } menu.ShowAsContext(); Event.current.Use(); } if (GUILayout.Button("RESET DEFAULTS")) { UserTypePrefs.ResetTypeConfiguration(); typeList = UserTypePrefs.GetPreferedTypesList(typeof(object)); Save(); } scrollPos = GUILayout.BeginScrollView(scrollPos); EditorUtils.ReorderableList(typeList, delegate(int i){ GUILayout.BeginHorizontal("box"); EditorGUILayout.LabelField(typeList[i].Name, typeList[i].Namespace); if (GUILayout.Button("X", GUILayout.Width(18))) { typeList.RemoveAt(i); Save(); } GUILayout.EndHorizontal(); }); GUILayout.EndScrollView(); Repaint(); }
/// <summary> /// Shows the context menu. /// </summary> protected virtual void OnContextMenu() { // Create the menu var menu = new UnityEditor.GenericMenu(); if (m_State != null) { // Set as start state if (m_State.fsm != null && !(m_State is InternalAnyState)) { menu.AddItem(new GUIContent("Set as Start"), false, delegate() { StateUtility.SetAsStart(m_State); this.Refresh(); }); } else { menu.AddDisabledItem(new GUIContent("Set as Start")); } // Set as concurrent state if (m_State.fsm != null && !(m_State is InternalAnyState)) { if (m_IsConcurrent) { menu.AddItem(new GUIContent("Set as Not Concurrent"), false, delegate() { StateUtility.RemoveConcurrentState(m_State.fsm); this.Refresh(); }); } else { menu.AddItem(new GUIContent("Set as Concurrent"), false, delegate() { StateUtility.SetAsConcurrent(m_State); this.Refresh(); }); } } else { menu.AddDisabledItem(new GUIContent("Set as Concurrent")); } // Set as enabled if (m_State.fsm != null /*&& m_State.fsm.enabled*/ && Application.isPlaying && !(m_State is InternalAnyState)) { menu.AddItem(new GUIContent("Set as Enabled"), false, delegate() { m_State.enabled = true; }); } else { menu.AddDisabledItem(new GUIContent("Set as Enabled")); } // Add Transitions // Add none menu.AddItem(new GUIContent("Add Transition/None"), false, delegate() { StateUtility.AddTransition(m_State, 0); CreateTransitionGUIs(); }); // Add blackboard events var blackboard = m_State.blackboard; if (blackboard != null) { foreach (var fsmEvent in blackboard.fsmEvents) { int eventId = fsmEvent.id; menu.AddItem(new GUIContent("Add Transition/" + fsmEvent.name), false, delegate() { StateUtility.AddTransition(m_State, eventId); CreateTransitionGUIs(); }); } } // Add GlobalBlackboard events // This is not The GlobalBlackboard? if (InternalGlobalBlackboard.Instance != null && blackboard != InternalGlobalBlackboard.Instance) { foreach (var globalEvent in InternalGlobalBlackboard.Instance.fsmEvents) { int eventId = globalEvent.id; var eventName = globalEvent.isSystem ? "Add Transition/System/" + globalEvent.name : "Add Transition/Global/" + globalEvent.name; menu.AddItem(new GUIContent(eventName), false, delegate() { StateUtility.AddTransition(m_State, eventId); CreateTransitionGUIs(); }); } } // Separator menu.AddSeparator(""); // Copy menu.AddItem(new GUIContent("Copy State"), false, delegate() { StateUtility.CopySelectedStates(); }); // Paste if (StateUtility.statesToPaste != null && StateUtility.statesToPaste.Length > 0 && m_State.fsm != null) { menu.AddItem(new GUIContent("Paste State"), false, delegate() { StateUtility.PasteStates(m_State.fsm); }); } else { menu.AddDisabledItem(new GUIContent("Paste State")); } // Duplicate if (m_State.fsm != null) { menu.AddItem(new GUIContent("Duplicate State"), false, delegate() { var statesToPaste = new List <InternalStateBehaviour>(BehaviourWindow.activeStates); if (!statesToPaste.Contains(m_State)) { statesToPaste.Add(m_State); } StateUtility.CloneStates(m_State.gameObject, statesToPaste.ToArray(), m_State.fsm); } ); } else { menu.AddDisabledItem(new GUIContent("Duplicate State")); } // Separator menu.AddSeparator(""); // Delete menu.AddItem(new GUIContent("Delete"), false, delegate() { StateUtility.Destroy(m_State); this.Refresh(); }); } else { menu.AddDisabledItem(new GUIContent("Set as Start")); menu.AddDisabledItem(new GUIContent("Set as Enabled")); menu.AddDisabledItem(new GUIContent("Add Transition")); menu.AddSeparator(""); menu.AddDisabledItem(new GUIContent("Copy State")); menu.AddDisabledItem(new GUIContent("Paste State")); menu.AddSeparator(""); menu.AddDisabledItem(new GUIContent("Delete")); } // Show the context menu menu.ShowAsContext(); }
public static void OnGui(MapEditor wind) { m_deletegroup.Clear(); LevelMapData data = wind.Level_Data; m_scroll = GUILayout.BeginScrollView(m_scroll); GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); GUILayout.Label(data.Name, GUILayout.Width(200)); GUILayout.Label("关卡数:" + data.Configs.Count, GUILayout.Width(300)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); bool isadd = false; if (isaddmode) { string temp = "0"; isadd = GUILayout.Button("确认"); GUILayout.Label("关卡ID", GUILayout.Width(50)); temp = GUILayout.TextField(id.ToString()); id = uint.Parse(temp); if (GUILayout.Button("取消")) { isaddmode = false; } } else { isaddmode = GUILayout.Button("添加关卡", GUILayout.Width(75)); GUILayout.Label("筛选关卡:", GUILayout.Width(50)); if (GUILayout.Button("清空", GUILayout.Width(40))) { wind.selectedLevel = string.Empty; } wind.selectedLevel = GUILayout.TextField(wind.selectedLevel, GUILayout.Width(50)); GUILayout.Space(10); if (GUILayout.Button("关卡类型", MapEditor.toolbarDropdown, GUILayout.Width(75))) { GenericMenu menu = new UnityEditor.GenericMenu(); //menu.AddSeparator(""); menu.AddItem(new GUIContent("全部"), false, () => { wind.selectedLevel_Type = 0; }); menu.AddItem(new GUIContent("冒险关卡"), false, () => { wind.selectedLevel_Type = 1; }); menu.AddItem(new GUIContent("签到关卡"), false, () => { wind.selectedLevel_Type = 2; }); //menu.DropDown(new Rect(0, 0, 20, 30)); menu.ShowAsContext(); } } if (isadd) { AddConfig(wind, id); isaddmode = false; } if (GUILayout.Button("编辑工具格子", GUILayout.Width(150))) { wind.Pagetype = MapEditor.PageType.EditorSub; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("地图ID", GUILayout.Width(200)); GUILayout.Label("对应的关卡ID", GUILayout.Width(250)); GUILayout.Label("规格:", GUILayout.Width(200)); GUILayout.EndHorizontal(); foreach (var k in data.Configs) { ConfigItem.OnGui(k, wind); } GUILayout.EndVertical(); GUILayout.EndScrollView(); if (m_deletegroup.Count > 0) { wind.Level_Data.DeleteConfig(m_deletegroup); } }
public static void HandleBindingDragAndDrop(TrackAsset dropTarget, Type requiredBindingType) { var objectBeingDragged = DragAndDrop.objectReferences[0]; var action = BindingUtility.GetBindingAction(requiredBindingType, objectBeingDragged); DragAndDrop.visualMode = action == BindingAction.DoNotBind ? DragAndDropVisualMode.Rejected : DragAndDropVisualMode.Link; if (action == BindingAction.DoNotBind || Event.current.type != EventType.DragPerform) { return; } var director = TimelineEditor.inspectedDirector; switch (action) { case BindingAction.BindDirectly: { BindingUtility.Bind(director, dropTarget, objectBeingDragged); break; } case BindingAction.BindToExistingComponent: { var gameObjectBeingDragged = objectBeingDragged as GameObject; Debug.Assert(gameObjectBeingDragged != null, "The object being dragged was detected as being a GameObject"); BindingUtility.Bind(director, dropTarget, gameObjectBeingDragged.GetComponent(requiredBindingType)); break; } case BindingAction.BindToMissingComponent: { var gameObjectBeingDragged = objectBeingDragged as GameObject; Debug.Assert(gameObjectBeingDragged != null, "The object being dragged was detected as being a GameObject"); var typeNameOfComponent = requiredBindingType.ToString().Split(".".ToCharArray()).Last(); var bindMenu = new GenericMenu(); bindMenu.AddItem( EditorGUIUtility.TextContent("Create " + typeNameOfComponent + " on " + gameObjectBeingDragged.name), false, nullParam => BindingUtility.Bind(director, dropTarget, Undo.AddComponent(gameObjectBeingDragged, requiredBindingType)), null); bindMenu.AddSeparator(""); bindMenu.AddItem(EditorGUIUtility.TrTextContent("Cancel"), false, userData => {}, null); bindMenu.ShowAsContext(); break; } default: { //no-op return; } } DragAndDrop.AcceptDrag(); }
internal static void ShaderErrorListUI(UnityEngine.Object shader, ShaderError[] errors, ref Vector2 scrollPosition) { int num = errors.Length; GUILayout.Space(5f); GUILayout.Label(string.Format("Errors ({0}):", num), EditorStyles.boldLabel, new GUILayoutOption[0]); #if UNITY_5_5_OR_NEWER int controlID = GUIUtility.GetControlID(CustomShaderInspector.kErrorViewHash, FocusType.Passive); #else int controlID = GUIUtility.GetControlID(CustomShaderInspector.kErrorViewHash, FocusType.Native); #endif float minHeight = Mathf.Min(( float )num * 20f + 40f, 150f); scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUISkinEx.GetCurrentSkin().box, new GUILayoutOption[] { GUILayout.MinHeight(minHeight) }); EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); float height = CustomShaderInspector.Styles.messageStyle.CalcHeight(EditorGUIUtilityEx.TempContent(CustomShaderInspector.Styles.errorIcon), 100f); Event current = Event.current; for (int i = 0; i < num; i++) { Rect controlRect = EditorGUILayout.GetControlRect(false, height, new GUILayoutOption[0]); string message = errors[i].message; string platform = errors[i].platform; bool flag = errors[i].warning != 0; string lastPathNameComponent = FileUtilEx.GetLastPathNameComponent(errors[i].file); int line = errors[i].line; if (current.type == EventType.MouseDown && current.button == 0 && controlRect.Contains(current.mousePosition)) { GUIUtility.keyboardControl = controlID; if (current.clickCount == 2) { string file = errors[i].file; UnityEngine.Object @object = (!string.IsNullOrEmpty(file)) ? AssetDatabase.LoadMainAssetAtPath(file) : null; AssetDatabase.OpenAsset(@object ?? shader, line); GUIUtility.ExitGUI(); } current.Use(); } if (current.type == EventType.ContextClick && controlRect.Contains(current.mousePosition)) { current.Use(); GenericMenu genericMenu = new GenericMenu(); int errorIndex = i; genericMenu.AddItem(new GUIContent("Copy error text"), false, delegate { string text = errors[errorIndex].message; if (!string.IsNullOrEmpty(errors[errorIndex].messageDetails)) { text += '\n'; text += errors[errorIndex].messageDetails; } EditorGUIUtility.systemCopyBuffer = text; }); genericMenu.ShowAsContext(); } if (current.type == EventType.Repaint && (i & 1) == 0) { GUIStyle evenBackground = CustomShaderInspector.Styles.evenBackground; evenBackground.Draw(controlRect, false, false, false, false); } Rect rect = controlRect; rect.xMin = rect.xMax; if (line > 0) { GUIContent content; if (string.IsNullOrEmpty(lastPathNameComponent)) { content = EditorGUIUtilityEx.TempContent(line.ToString(CultureInfo.InvariantCulture)); } else { content = EditorGUIUtilityEx.TempContent(lastPathNameComponent + ":" + line.ToString(CultureInfo.InvariantCulture)); } Vector2 vector = EditorStyles.miniLabel.CalcSize(content); rect.xMin -= vector.x; GUI.Label(rect, content, EditorStyles.miniLabel); rect.xMin -= 2f; if (rect.width < 30f) { rect.xMin = rect.xMax - 30f; } } Rect position = rect; position.width = 0f; if (platform.Length > 0) { GUIContent content2 = EditorGUIUtilityEx.TempContent(platform); Vector2 vector2 = EditorStyles.miniLabel.CalcSize(content2); position.xMin -= vector2.x; Color contentColor = GUI.contentColor; GUI.contentColor = new Color(1f, 1f, 1f, 0.5f); GUI.Label(position, content2, EditorStyles.miniLabel); GUI.contentColor = contentColor; position.xMin -= 2f; } Rect position2 = controlRect; position2.xMax = position.xMin; GUI.Label(position2, EditorGUIUtilityEx.TempContent(message, (!flag) ? CustomShaderInspector.Styles.errorIcon : CustomShaderInspector.Styles.warningIcon), CustomShaderInspector.Styles.messageStyle); } EditorGUIUtility.SetIconSize(Vector2.zero); GUILayout.EndScrollView(); }
public override void Draw() { float width = UnityEditor.EditorGUIUtility.labelWidth; using (new GUILayout.HorizontalScope()) { GUILayout.Label("Search Name", GUILayout.Width(width)); search = GUILayout.TextField(search); } using (new GUILayout.HorizontalScope()) { GUILayout.Label("Filter", GUILayout.Width(width)); if (GUILayout.Button(filter == null ? "No Filter" : filter.Name, UnityEditor.EditorStyles.toolbarDropDown)) { var menu = new UnityEditor.GenericMenu(); var items = new List <Type>(AllGroups.Keys); items.Remove(typeof(GameSystem)); items.Sort((x, y) => y.Name.CompareTo(x.Name)); items.Add(typeof(GameSystem)); for (int i = items.Count - 1; i >= 0; --i) { var item = items[i]; menu.AddItem(new GUIContent(item.Name), filter == item, () => filter = item); } menu.ShowAsContext(); } } if (AllGroups.TryGetValue(filter, out var group)) { using (new GUILayout.VerticalScope(UnityEditor.EditorStyles.helpBox)) { using (new GUILayout.HorizontalScope()) { GUILayout.Label("Priority", UnityEditor.EditorStyles.boldLabel, GUILayout.Width(64f)); GUILayout.Label("Game System", UnityEditor.EditorStyles.boldLabel); } foreach (var item in group.List) { if (item.GetType().Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0) { using (new GUILayout.HorizontalScope()) { GUILayout.Label(((int)item.GetType().GetCustomAttribute <Priority>()).ToString(), GUILayout.Width(64f)); using (new GUILayout.VerticalScope()) { if (GUILayout.Button(item.GetType().Name, UnityEditor.EditorStyles.label)) { if (item is IOnInspect inspectable) { if (inspected.Contains(inspectable)) { inspected.Remove(inspectable); } else { inspected.Add(inspectable); } } } if (inspected.Contains(item as IOnInspect)) { using (new GUILayout.VerticalScope(UnityEditor.EditorStyles.helpBox)) { (item as IOnInspect).OnInspect(); } } } } } } } } }
internal static void DoToolContextMenu() { var toolHistoryMenu = new GenericMenu() { allowDuplicateNames = true }; var foundTool = false; // Recent history if (EditorToolContext.GetLastCustomTool() != null) { foundTool = true; toolHistoryMenu.AddDisabledItem(Styles.recentTools); EditorToolContext.GetToolHistory(s_ToolList, true); for (var i = 0; i < Math.Min(k_MaxToolHistory, s_ToolList.Count); i++) { var tool = s_ToolList[i]; if (EditorToolUtility.IsCustomEditorTool(tool.GetType())) { continue; } var name = EditorToolUtility.GetToolName(tool.GetType()); if (tool.IsAvailable()) { toolHistoryMenu.AddItem(new GUIContent(name), false, () => { EditorToolContext.activeTool = tool; }); } else { toolHistoryMenu.AddDisabledItem(new GUIContent(name)); } } toolHistoryMenu.AddSeparator(""); } EditorToolContext.GetCustomEditorTools(s_ToolList, false); // Current selection if (s_ToolList.Any()) { foundTool = true; toolHistoryMenu.AddDisabledItem(Styles.selectionTools); for (var i = 0; i < s_ToolList.Count; i++) { var tool = s_ToolList[i]; if (!EditorToolUtility.IsCustomEditorTool(tool.GetType())) { continue; } var path = new GUIContent(EditorToolUtility.GetToolMenuPath(tool)); if (tool.IsAvailable()) { toolHistoryMenu.AddItem(path, false, () => { EditorToolContext.activeTool = tool; }); } else { toolHistoryMenu.AddDisabledItem(path); } } toolHistoryMenu.AddSeparator(""); } var global = EditorToolUtility.GetCustomEditorToolsForType(null); if (global.Any()) { foundTool = true; toolHistoryMenu.AddDisabledItem(Styles.availableTools); foreach (var toolType in global) { toolHistoryMenu.AddItem( new GUIContent(EditorToolUtility.GetToolMenuPath(toolType)), false, () => { EditorTools.EditorTools.SetActiveTool(toolType); }); } } if (!foundTool) { toolHistoryMenu.AddDisabledItem(Styles.noToolsAvailable); } toolHistoryMenu.ShowAsContext(); }
/// <summary> /// Provides input handling for the panel /// </summary> public override void ProcessInput() { Event lCurrentEvent = Event.current; EventType lCurrentEventType = lCurrentEvent.type; Node lClickedNode = null; NodeLink lClickedLink = null; switch (lCurrentEventType) { // Handles keypresses case EventType.KeyUp: switch (lCurrentEvent.keyCode) { case KeyCode.Delete: if (GUIUtility.keyboardControl == 0) { if (mSelectedNode != null) { RemoveNode(mSelectedNode); } if (mSelectedLink != null) { RemoveLink(mSelectedLink); } Editor.Repaint(); } break; } break; // Handles the mouse down event case EventType.MouseDown: for (int i = 0; i < Nodes.Count; i++) { if (Nodes[i].ContainsPoint(lCurrentEvent.mousePosition)) { lClickedLink = null; lClickedNode = Nodes[i]; } if (lClickedNode == null) { for (int j = 0; j < Nodes[i].Links.Count; j++) { if (Nodes[i].Links[j].ContainsPoint(lCurrentEvent.mousePosition)) { lClickedLink = Nodes[i].Links[j]; break; } } } if (lClickedNode != null || lClickedLink != null) { break; } } mIsPanning = false; // With left mouse button, select if (lCurrentEvent.button == 0) { if (mIsLinking && mActiveLink != null) { if (lClickedNode != null && lClickedNode != mActiveLink.StartNode) { mActiveLink.EndNode = lClickedNode; AddLink(mActiveLink); } mActiveLink = null; mActiveNode = null; mSelectedNode = null; } else { if (lClickedNode != null) { GUIUtility.keyboardControl = 0; } if (lClickedNode != mSelectedNode && NodeSelectedEvent != null) { NodeSelectedEvent(lClickedNode); } if (lClickedLink != null) { GUIUtility.keyboardControl = 0; } if (lClickedLink != mSelectedLink && LinkSelectedEvent != null) { LinkSelectedEvent(lClickedLink); } mActiveNode = lClickedNode; mSelectedNode = lClickedNode; mActiveLink = lClickedLink; mSelectedLink = lClickedLink; if (lClickedNode != null) { mDragStart = lCurrentEvent.mousePosition; mDragOffset = Vector2.zero; } } mIsLinking = false; Editor.Repaint(); } // With right mouse button, show the menu else if (lCurrentEvent.button == 1) { mActiveNode = lClickedNode; mActiveLink = lClickedLink; if (mActiveNode != null) { GenericMenu lMenu = new UnityEditor.GenericMenu(); lMenu.AddItem(new GUIContent("Add Link"), false, OnStartAddLink, mActiveNode); lMenu.AddSeparator(""); lMenu.AddItem(new GUIContent("Delete Node"), false, OnRemoveNode, mActiveNode); lMenu.ShowAsContext(); lCurrentEvent.Use(); } else if (mActiveLink != null) { GenericMenu lMenu = new UnityEditor.GenericMenu(); lMenu.AddItem(new GUIContent("Delete Link"), false, OnRemoveLink, mActiveLink); lMenu.ShowAsContext(); lCurrentEvent.Use(); } else { GenericMenu lMenu = new UnityEditor.GenericMenu(); lMenu.AddItem(new GUIContent("Add Node"), false, OnAddNode, typeof(Node)); lMenu.ShowAsContext(); lCurrentEvent.Use(); } } // With right mouse buttion, drag the canvas else if (lCurrentEvent.button == 2) { mIsPanning = true; mDragStart = lCurrentEvent.mousePosition; mDragOffset = Vector2.zero; } break; // Handles the mouse drag event case EventType.MouseDrag: // Pan the canvas as needed if (mIsPanning) { Vector2 lDragOffset = mDragOffset; mDragOffset = lCurrentEvent.mousePosition - mDragStart; Vector2 lOffset = (mDragOffset - lDragOffset) * mZoom; mPanOffset = mPanOffset + lOffset; Editor.Repaint(); } // Move the active node as needed else if (mActiveNode != null) { Vector2 lDragOffset = mDragOffset; mDragOffset = lCurrentEvent.mousePosition - mDragStart; Vector2 lOffset = (mDragOffset - lDragOffset) * mZoom; mActiveNode.Position.x = mActiveNode.Position.x + lOffset.x; mActiveNode.Position.y = mActiveNode.Position.y + lOffset.y; Editor.Repaint(); } break; // Handles the mouse up event case EventType.MouseUp: if (mActiveNode != null) { if (mDragOffset.sqrMagnitude > 0f) { mDragOffset = Vector2.zero; // Reorder the links left to right for (int i = 0; i < Nodes.Count; i++) { bool lReorder = false; for (int j = 0; j < Nodes[i].Links.Count; j++) { if (Nodes[i].Links[j].EndNode == mActiveNode) { lReorder = true; break; } } if (lReorder) { Nodes[i].Links = Nodes[i].Links.OrderBy(x => x.EndNode.Position.x).ToList <NodeLink>(); } } // Flag the canvas as dirty EditorUtility.SetDirty(mActiveNode); SetDirty(); } } // Ensure we don't pan or move a node mIsPanning = false; mActiveNode = null; break; } }
public void EventLineGUI(Rect rect, AnimationWindowState state) { AnimationClip activeAnimationClip = state.activeAnimationClip; GameObject activeRootGameObject = state.activeRootGameObject; GUI.BeginGroup(rect); Color color = GUI.color; Rect rect2 = new Rect(0f, 0f, rect.width, rect.height); float time = Mathf.Max((float)Mathf.RoundToInt(state.PixelToTime(Event.current.mousePosition.x, rect) * state.frameRate) / state.frameRate, 0f); if (activeAnimationClip != null) { AnimationEvent[] animationEvents = AnimationUtility.GetAnimationEvents(activeAnimationClip); Texture image = EditorGUIUtility.IconContent("Animation.EventMarker").image; Rect[] array = new Rect[animationEvents.Length]; Rect[] array2 = new Rect[animationEvents.Length]; int num = 1; int num2 = 0; for (int i = 0; i < animationEvents.Length; i++) { AnimationEvent animationEvent = animationEvents[i]; if (num2 == 0) { num = 1; while (i + num < animationEvents.Length && animationEvents[i + num].time == animationEvent.time) { num++; } num2 = num; } num2--; float num3 = Mathf.Floor(state.FrameToPixel(animationEvent.time * activeAnimationClip.frameRate, rect)); int num4 = 0; if (num > 1) { float num5 = (float)Mathf.Min((num - 1) * (image.width - 1), (int)(state.FrameDeltaToPixel(rect) - (float)(image.width * 2))); num4 = Mathf.FloorToInt(Mathf.Max(0f, num5 - (float)((image.width - 1) * num2))); } Rect rect3 = new Rect(num3 + (float)num4 - (float)(image.width / 2), (rect.height - 10f) * (float)(num2 - num + 1) / (float)Mathf.Max(1, num - 1), (float)image.width, (float)image.height); array[i] = rect3; array2[i] = rect3; } if (this.m_DirtyTooltip) { if (this.m_HoverEvent >= 0 && this.m_HoverEvent < array.Length) { this.m_InstantTooltipText = AnimationWindowEventInspector.FormatEvent(activeRootGameObject, animationEvents[this.m_HoverEvent]); this.m_InstantTooltipPoint = new Vector2(array[this.m_HoverEvent].xMin + (float)((int)(array[this.m_HoverEvent].width / 2f)) + rect.x - 30f, rect.yMax); } this.m_DirtyTooltip = false; } bool[] array3 = new bool[animationEvents.Length]; UnityEngine.Object[] objects = Selection.objects; UnityEngine.Object[] array4 = objects; for (int j = 0; j < array4.Length; j++) { UnityEngine.Object @object = array4[j]; AnimationWindowEvent animationWindowEvent = @object as AnimationWindowEvent; if (animationWindowEvent != null) { if (animationWindowEvent.eventIndex >= 0 && animationWindowEvent.eventIndex < array3.Length) { array3[animationWindowEvent.eventIndex] = true; } } } Vector2 zero = Vector2.zero; int num6; float num7; float num8; HighLevelEvent highLevelEvent = EditorGUIExt.MultiSelection(rect, array2, new GUIContent(image), array, ref array3, null, out num6, out zero, out num7, out num8, GUIStyle.none); if (highLevelEvent != HighLevelEvent.None) { switch (highLevelEvent) { case HighLevelEvent.DoubleClick: if (num6 != -1) { this.EditEvents(activeRootGameObject, activeAnimationClip, array3); } else { this.EventLineContextMenuAdd(new AnimationEventTimeLine.EventLineContextMenuObject(activeRootGameObject, activeAnimationClip, time, -1, array3)); } break; case HighLevelEvent.ContextClick: { GenericMenu genericMenu = new GenericMenu(); AnimationEventTimeLine.EventLineContextMenuObject userData = new AnimationEventTimeLine.EventLineContextMenuObject(activeRootGameObject, activeAnimationClip, animationEvents[num6].time, num6, array3); int num9 = array3.Count((bool selected) => selected); genericMenu.AddItem(EditorGUIUtility.TrTextContent("Add Animation Event", null, null), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuAdd), userData); genericMenu.AddItem(new GUIContent((num9 <= 1) ? "Delete Animation Event" : "Delete Animation Events"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuDelete), userData); genericMenu.ShowAsContext(); this.m_InstantTooltipText = null; this.m_DirtyTooltip = true; state.Repaint(); break; } case HighLevelEvent.BeginDrag: this.m_EventsAtMouseDown = animationEvents; this.m_EventTimes = new float[animationEvents.Length]; for (int k = 0; k < animationEvents.Length; k++) { this.m_EventTimes[k] = animationEvents[k].time; } break; case HighLevelEvent.Drag: { for (int l = animationEvents.Length - 1; l >= 0; l--) { if (array3[l]) { AnimationEvent animationEvent2 = this.m_EventsAtMouseDown[l]; animationEvent2.time = this.m_EventTimes[l] + zero.x * state.PixelDeltaToTime(rect); animationEvent2.time = Mathf.Max(0f, animationEvent2.time); animationEvent2.time = (float)Mathf.RoundToInt(animationEvent2.time * activeAnimationClip.frameRate) / activeAnimationClip.frameRate; } } int[] array5 = new int[array3.Length]; for (int m = 0; m < array5.Length; m++) { array5[m] = m; } Array.Sort(this.m_EventsAtMouseDown, array5, new AnimationEventTimeLine.EventComparer()); bool[] array6 = (bool[])array3.Clone(); float[] array7 = (float[])this.m_EventTimes.Clone(); for (int n = 0; n < array5.Length; n++) { array3[n] = array6[array5[n]]; this.m_EventTimes[n] = array7[array5[n]]; } this.EditEvents(activeRootGameObject, activeAnimationClip, array3); Undo.RegisterCompleteObjectUndo(activeAnimationClip, "Move Event"); AnimationUtility.SetAnimationEvents(activeAnimationClip, this.m_EventsAtMouseDown); this.m_DirtyTooltip = true; break; } case HighLevelEvent.Delete: this.DeleteEvents(activeAnimationClip, array3); break; case HighLevelEvent.SelectionChanged: state.ClearKeySelections(); this.EditEvents(activeRootGameObject, activeAnimationClip, array3); break; } } this.CheckRectsOnMouseMove(rect, animationEvents, array); if (Event.current.type == EventType.ContextClick && rect2.Contains(Event.current.mousePosition)) { Event.current.Use(); GenericMenu genericMenu2 = new GenericMenu(); AnimationEventTimeLine.EventLineContextMenuObject userData2 = new AnimationEventTimeLine.EventLineContextMenuObject(activeRootGameObject, activeAnimationClip, time, -1, array3); int num10 = array3.Count((bool selected) => selected); genericMenu2.AddItem(EditorGUIUtility.TrTextContent("Add Animation Event", null, null), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuAdd), userData2); if (num10 > 0) { genericMenu2.AddItem(new GUIContent((num10 <= 1) ? "Delete Animation Event" : "Delete Animation Events"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuDelete), userData2); } genericMenu2.ShowAsContext(); } } GUI.color = color; GUI.EndGroup(); }
public void OnTransformInspectorGUI() { float left = 0, top = 0, right = 0, bottom = 0; // Don't make toggling foldout cause GUI.changed to be true (shouldn't cause undoable action etc.) bool wasChanged = GUI.changed; m_TransformMaskFoldout = EditorGUILayout.Foldout(m_TransformMaskFoldout, Styles.TransformMask, true); GUI.changed = wasChanged; if (m_TransformMaskFoldout) { if (canImport) { ImportAvatarReference(); } if (m_NodeInfos == null || m_TransformMask.arraySize != m_NodeInfos.Length) { FillNodeInfos(); } if (IsMaskEmpty()) { GUILayout.BeginVertical(); GUILayout.BeginHorizontal(EditorStyles.helpBox); string message; if (animationType == ModelImporterAnimationType.Generic) { message = "No transform mask defined, everything will be imported"; } else if (animationType == ModelImporterAnimationType.Human) { message = "No transform mask defined, only human curves will be imported"; } else { message = "No transform mask defined"; } GUILayout.Label(message, EditorStyles.wordWrappedMiniLabel); GUILayout.EndHorizontal(); if (!canImport && clipInfo.maskType == ClipAnimationMaskType.CreateFromThisModel) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); string fixMaskButtonLabel = "Create Mask"; if (GUILayout.Button(fixMaskButtonLabel)) { UpdateMask(clipInfo.maskType); } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); } else { ComputeShownElements(); GUILayout.Space(1); int prevIndent = EditorGUI.indentLevel; int size = m_TransformMask.arraySize; for (int i = 1; i < size; i++) { if (m_NodeInfos[i].m_Show) { GUILayout.BeginHorizontal(); EditorGUI.indentLevel = m_NodeInfos[i].m_Depth + 1; EditorGUI.BeginChangeCheck(); Rect toggleRect = GUILayoutUtility.GetRect(15, 15, GUILayout.ExpandWidth(false)); GUILayoutUtility.GetRect(10, 15, GUILayout.ExpandWidth(false)); toggleRect.x += 15; EditorGUI.BeginDisabledGroup(m_NodeInfos[i].m_State == NodeInfo.State.disabled || m_NodeInfos[i].m_State == NodeInfo.State.invalid); bool rightClick = Event.current.button == 1; bool isActive = m_NodeInfos[i].m_Weight.floatValue > 0.0f; isActive = GUI.Toggle(toggleRect, isActive, ""); if (EditorGUI.EndChangeCheck()) { m_NodeInfos[i].m_Weight.floatValue = isActive ? 1.0f : 0.0f; if (!rightClick) { CheckChildren(i, isActive); } } string textValue; if (m_NodeInfos[i].m_State == NodeInfo.State.invalid) { textValue = "<color=#FF0000AA>" + m_NodeInfos[i].m_Name + "</color>"; } else { textValue = m_NodeInfos[i].m_Name; } if (m_NodeInfos[i].m_ChildIndices.Count > 0) { m_NodeInfos[i].m_Expanded = EditorGUILayout.Foldout(m_NodeInfos[i].m_Expanded, textValue, true, Styles.foldoutStyle); } else { EditorGUILayout.LabelField(textValue, Styles.labelStyle); } EditorGUI.EndDisabledGroup(); if (i == 1) { top = toggleRect.yMin; left = toggleRect.xMin; } else if (i == size - 1) { bottom = toggleRect.yMax; } right = Mathf.Max(right, GUILayoutUtility.GetLastRect().xMax); GUILayout.EndHorizontal(); } } EditorGUI.indentLevel = prevIndent; } } Rect bounds = Rect.MinMaxRect(left, top, right, bottom); if (Event.current != null && Event.current.type == EventType.MouseUp && Event.current.button == 1 && bounds.Contains(Event.current.mousePosition)) { var menu = new GenericMenu(); menu.AddItem(EditorGUIUtility.TrTextContent("Select all"), false, SelectAll); menu.AddItem(EditorGUIUtility.TrTextContent("Deselect all"), false, DeselectAll); menu.ShowAsContext(); Event.current.Use(); } }
internal static void ShaderErrorListUI(UnityEngine.Object shader, ShaderError[] errors, ref Vector2 scrollPosition) { // ISSUE: object of a compiler-generated type is created // ISSUE: variable of a compiler-generated type ShaderInspector.\u003CShaderErrorListUI\u003Ec__AnonStorey9A listUiCAnonStorey9A = new ShaderInspector.\u003CShaderErrorListUI\u003Ec__AnonStorey9A(); // ISSUE: reference to a compiler-generated field listUiCAnonStorey9A.errors = errors; // ISSUE: reference to a compiler-generated field int length = listUiCAnonStorey9A.errors.Length; GUILayout.Space(5f); GUILayout.Label(string.Format("Errors ({0}):", (object)length), EditorStyles.boldLabel, new GUILayoutOption[0]); int controlId = GUIUtility.GetControlID(ShaderInspector.kErrorViewHash, FocusType.Native); float minHeight = Mathf.Min((float)((double)length * 20.0 + 40.0), 150f); scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUISkin.current.box, GUILayout.MinHeight(minHeight)); EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); float height = ShaderInspector.Styles.messageStyle.CalcHeight(EditorGUIUtility.TempContent((Texture)ShaderInspector.Styles.errorIcon), 100f); Event current = Event.current; for (int index = 0; index < length; ++index) { Rect controlRect = EditorGUILayout.GetControlRect(false, height, new GUILayoutOption[0]); // ISSUE: reference to a compiler-generated field string message = listUiCAnonStorey9A.errors[index].message; // ISSUE: reference to a compiler-generated field string platform = listUiCAnonStorey9A.errors[index].platform; // ISSUE: reference to a compiler-generated field bool flag = listUiCAnonStorey9A.errors[index].warning != 0; // ISSUE: reference to a compiler-generated field string pathNameComponent = FileUtil.GetLastPathNameComponent(listUiCAnonStorey9A.errors[index].file); // ISSUE: reference to a compiler-generated field int line = listUiCAnonStorey9A.errors[index].line; if (current.type == EventType.MouseDown && current.button == 0 && controlRect.Contains(current.mousePosition)) { GUIUtility.keyboardControl = controlId; if (current.clickCount == 2) { // ISSUE: reference to a compiler-generated field string file = listUiCAnonStorey9A.errors[index].file; UnityEngine.Object target = !string.IsNullOrEmpty(file) ? AssetDatabase.LoadMainAssetAtPath(file) : (UnityEngine.Object)null; if ((object)target == null) { target = shader; } int lineNumber = line; AssetDatabase.OpenAsset(target, lineNumber); GUIUtility.ExitGUI(); } current.Use(); } if (current.type == EventType.ContextClick && controlRect.Contains(current.mousePosition)) { // ISSUE: object of a compiler-generated type is created // ISSUE: variable of a compiler-generated type ShaderInspector.\u003CShaderErrorListUI\u003Ec__AnonStorey9B listUiCAnonStorey9B = new ShaderInspector.\u003CShaderErrorListUI\u003Ec__AnonStorey9B(); // ISSUE: reference to a compiler-generated field listUiCAnonStorey9B.\u003C\u003Ef__ref\u0024154 = listUiCAnonStorey9A; current.Use(); GenericMenu genericMenu = new GenericMenu(); // ISSUE: reference to a compiler-generated field listUiCAnonStorey9B.errorIndex = index; // ISSUE: reference to a compiler-generated method genericMenu.AddItem(new GUIContent("Copy error text"), false, new GenericMenu.MenuFunction(listUiCAnonStorey9B.\u003C\u003Em__1B2)); genericMenu.ShowAsContext(); } if (current.type == EventType.Repaint && (index & 1) == 0) { ShaderInspector.Styles.evenBackground.Draw(controlRect, false, false, false, false); } Rect position1 = controlRect; position1.xMin = position1.xMax; if (line > 0) { GUIContent content = !string.IsNullOrEmpty(pathNameComponent) ? EditorGUIUtility.TempContent(pathNameComponent + ":" + line.ToString((IFormatProvider)CultureInfo.InvariantCulture)) : EditorGUIUtility.TempContent(line.ToString((IFormatProvider)CultureInfo.InvariantCulture)); Vector2 vector2 = EditorStyles.miniLabel.CalcSize(content); position1.xMin -= vector2.x; GUI.Label(position1, content, EditorStyles.miniLabel); position1.xMin -= 2f; if ((double)position1.width < 30.0) { position1.xMin = position1.xMax - 30f; } } Rect position2 = position1; position2.width = 0.0f; if (platform.Length > 0) { GUIContent content = EditorGUIUtility.TempContent(platform); Vector2 vector2 = EditorStyles.miniLabel.CalcSize(content); position2.xMin -= vector2.x; Color contentColor = GUI.contentColor; GUI.contentColor = new Color(1f, 1f, 1f, 0.5f); GUI.Label(position2, content, EditorStyles.miniLabel); GUI.contentColor = contentColor; position2.xMin -= 2f; } Rect position3 = controlRect; position3.xMax = position2.xMin; GUI.Label(position3, EditorGUIUtility.TempContent(message, !flag ? (Texture)ShaderInspector.Styles.errorIcon : (Texture)ShaderInspector.Styles.warningIcon), ShaderInspector.Styles.messageStyle); } EditorGUIUtility.SetIconSize(Vector2.zero); GUILayout.EndScrollView(); }
void OnGUI() { EditorGUILayout.BeginHorizontal(); Rect dropdownbuttonRect = new Rect(0, 0, 70, 20); var _contentRect = contentRect; _contentRect.height = (zoo.animals.Count + 1) * 20; EditorGUI.DrawRect(zoneRect, new Color(0.2f, 0.2f, 0.2f)); //GUILayout.BeginArea(zoneRect, GUI.skin.box); sp = GUI.BeginScrollView(zoneRect, sp, _contentRect); //GUI.Label(new Rect(100, 200, Screen.width, 50), "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); GUILayout.BeginArea(_contentRect); EditorGUILayout.LabelField("animal count", zoo.animals.Count.ToString()); for (int i = 0; i < zoo.animals.Count; i++) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(i.ToString(), zoo.animals[i].Species); if (EditorGUILayout.DropdownButton(new GUIContent(m_Type[zoo.animals[i].type]), FocusType.Passive)) { GenericMenu menu = new GenericMenu(); for (int j = 0; j < m_Type.Length; j++) { var info = new ClickInfo { index = i, type = j }; menu.AddItem(new GUIContent(m_Type[j]), false, ItemCallBack2, info); } //menu.DropDown(GUILayoutUtility.GetLastRect()); menu.ShowAsContext(); } if (GUILayout.Button("remove", GUILayout.Width(70))) { zoo.animals.RemoveAt(i); } EditorGUILayout.EndHorizontal(); } GUILayout.EndArea(); GUI.EndScrollView(); EditorGUILayout.EndHorizontal(); //GUILayout.EndArea(); GUILayout.BeginArea(buttonRect, GUI.skin.box); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("add Cat")) { zoo.animals.Add(new Cat()); } if (GUILayout.Button("add Dog")) { zoo.animals.Add(new Dog()); } if (GUILayout.Button("add Giraffe")) { zoo.animals.Add(new Giraffe()); } EditorGUILayout.EndHorizontal(); GUILayout.EndArea(); GUILayout.BeginArea(dropdownButtonRect, GUI.skin.box); EditorGUILayout.BeginHorizontal(); if (EditorGUILayout.DropdownButton(new GUIContent(m_Type[selectedType]), FocusType.Passive)) { GenericMenu menu = new GenericMenu(); for (int i = 0; i < m_Type.Length; i++) { menu.AddItem(new GUIContent(m_Type[i]), false, ItemCallBack, i); } menu.ShowAsContext(); } //GUILayout.FlexibleSpace(); this.selectedOption = EditorGUILayout.Popup("Popup", (int)this.selectedOption, new string[] { "s1", "s2", "s3" }); if (GUILayout.Button("Select Animation")) { AnimationClip fbxObj = AssetDatabase.LoadAssetAtPath <AnimationClip>("Assets/Data/Emotes--RussianDance.anim.fbx"); Selection.activeObject = fbxObj; } //Set certain model to the AvatarPreview window if (GUILayout.Button("Set Model")) { SetSelectModel("Assets/Data/Robot_A.fbx"); } EditorGUILayout.EndHorizontal(); GUILayout.EndArea(); }
void DoTrackContextMenu(Event e, Rect clipsPosRect, float cursorTime, System.Action action, System.Action <Track> onDragUpdated, System.Action <Track, float> onDragPerform) { if (e.type == EventType.ContextClick && clipsPosRect.Contains(e.mousePosition)) { var attachableTypeInfos = new List <EditorTools.TypeMetaInfo>(); foreach (var info in EditorTools.GetTypeMetaDerivedFrom(typeof(Clip), Prefs.isOld)) { if (info.attachableTypes != null && !info.attachableTypes.Contains(this.GetType())) { continue; } if (info.type != typeof(Clip)) { attachableTypeInfos.Add(info); } } var menu = new UnityEditor.GenericMenu(); if (attachableTypeInfos.Count > 0) { foreach (var _info in attachableTypeInfos) { var info = _info; var tName = info.name; menu.AddItem(new GUIContent(tName), false, () => { var clip = ReflectionTools.CreateInstance(_info.type) as Clip; clip.startTime = cursorTime; AddNode(clip); CutsceneUtility.selectedObject = clip; if (action != null) { action(); } }); } e.Use(); } if (CutsceneUtility.CanPastClip(attachableTypeInfos)) { menu.AddItem(new GUIContent("粘贴"), false, () => { CutsceneUtility.PasteClip(this, cursorTime); }); } if (menu.GetItemCount() > 0) { menu.ShowAsContext(); } else { menu = null; } } if (clipsPosRect.Contains(e.mousePosition) && e.type == EventType.DragUpdated) { if (onDragUpdated != null) { onDragUpdated(this); } } if (clipsPosRect.Contains(e.mousePosition) && e.type == EventType.DragPerform) { if (onDragPerform != null) { onDragPerform(this, cursorTime); } //for (int i = 0; i < DragAndDrop.objectReferences.Length; i++) //{ // var o = DragAndDrop.objectReferences[i]; // if (o is AnimationClip && this is SkillAnimationTrack) // { // var aniClip = new SKillAnimationEvent(); // AddNode(aniClip); // aniClip.startTime = cursorTime; // aniClip.length = (o as AnimationClip).length; // aniClip.animationClip = o as AnimationClip; // if (action != null) action(); // CutsceneUtility.selectedObject = aniClip; // } //} SortClips(); } }
void OnGUI() { EditorGUILayout.HelpBox("Here you can specify frequently used types for your game for easier access wherever you need to select a type, like for example when you create a new blackboard variable or using any refelection based actions. Furthermore, it is essential when working with AOT platforms like iOS or WebGL, that you generate an AOT Classes and link.xml files with the relevant button bellow.\nTo add types in the list quicker, you can also Drag&Drop an object, or a Script file in this editor window, or seach it bellow.", MessageType.Info); GUILayout.BeginHorizontal(); search = EditorGUILayout.TextField(search, (GUIStyle)"ToolbarSeachTextField"); if (GUILayout.Button("", (GUIStyle)"ToolbarSeachCancelButton")) { search = null; GUIUtility.keyboardControl = 0; } GUILayout.EndHorizontal(); if (search != null && search.Length > 2) { GUILayout.Label(string.Format("<b>{0}</b>", "Showing Search Results. Click the plus button to add the type.")); GUILayout.Space(5); scrollPos = GUILayout.BeginScrollView(scrollPos); foreach (var type in EditorUtils.GetAssemblyTypes(typeof(object))) { if (type.Name.ToUpper().Contains(search.ToUpper())) { GUILayout.BeginHorizontal("box"); if (GUILayout.Button("+", GUILayout.Width(20))) { AddType(type); } EditorGUILayout.LabelField(type.Name, type.Namespace); GUILayout.EndHorizontal(); } } GUILayout.EndScrollView(); return; } if (GUILayout.Button("Add New Type")) { GenericMenu.MenuFunction2 Selected = delegate(object o){ if (o is System.Type) { AddType((System.Type)o); } if (o is string) //namespace { foreach (var type in EditorUtils.GetAssemblyTypes(typeof(object))) { if (type.Namespace == (string)o) { AddType(type); } } } }; var menu = new UnityEditor.GenericMenu(); menu.AddItem(new GUIContent("Classes/System/Object"), false, Selected, typeof(object)); foreach (var t in EditorUtils.GetAssemblyTypes(typeof(object))) { var friendlyName = (string.IsNullOrEmpty(t.Namespace)? "No Namespace/" : t.Namespace.Replace(".", "/") + "/") + t.FriendlyName(); var category = "Classes/"; if (t.IsInterface) { category = "Interfaces/"; } if (t.IsEnum) { category = "Enumerations/"; } menu.AddItem(new GUIContent(category + friendlyName), false, Selected, t); if (t.Namespace != null) { var ns = t.Namespace.Replace(".", "/"); menu.AddItem(new GUIContent("Namespaces/" + ns), false, Selected, t.Namespace); } } menu.ShowAsContext(); Event.current.Use(); } #if !UNITY_WEBPLAYER if (GUILayout.Button("Generate AOTClasses.cs and link.xml Files")) { if (EditorUtility.DisplayDialog("Generate AOT Classes", "A script relevant to AOT compatibility for certain platforms will now be generated.", "OK")) { var path = EditorUtility.SaveFilePanelInProject("AOT Classes File", "AOTClasses", "cs", ""); if (!string.IsNullOrEmpty(path)) { AOTClassesGenerator.GenerateAOTClasses(path); } } if (EditorUtility.DisplayDialog("Generate link.xml File", "A file relevant to 'code stripping' for platforms that have code stripping enabled will now be generated.", "OK")) { var path = EditorUtility.SaveFilePanelInProject("AOT link.xml", "link", "xml", ""); if (!string.IsNullOrEmpty(path)) { AOTClassesGenerator.GenerateLinkXML(path); } } AssetDatabase.Refresh(); } GUILayout.BeginHorizontal(); if (GUILayout.Button("RESET DEFAULTS")) { if (EditorUtility.DisplayDialog("Reset Preferred Types", "Are you sure?", "Yes", "NO!")) { UserTypePrefs.ResetTypeConfiguration(); typeList = UserTypePrefs.GetPreferedTypesList(typeof(object)); Save(); } } if (GUILayout.Button("Save Preset")) { var path = EditorUtility.SaveFilePanelInProject("Save Types Preset", "", "typePrefs", ""); if (!string.IsNullOrEmpty(path)) { System.IO.File.WriteAllText(path, JSONSerializer.Serialize(typeof(List <System.Type>), typeList, true)); AssetDatabase.Refresh(); } } if (GUILayout.Button("Load Preset")) { var path = EditorUtility.OpenFilePanel("Load Types Preset", "Assets", "typePrefs"); if (!string.IsNullOrEmpty(path)) { var json = System.IO.File.ReadAllText(path); typeList = JSONSerializer.Deserialize <List <System.Type> >(json); Save(); } } GUILayout.EndHorizontal(); #endif GUILayout.Space(5); scrollPos = GUILayout.BeginScrollView(scrollPos); for (int i = 0; i < typeList.Count; i++) { GUILayout.BeginHorizontal("box"); EditorGUILayout.LabelField(typeList[i].Name, typeList[i].Namespace); if (GUILayout.Button("X", GUILayout.Width(18))) { RemoveType(typeList[i]); } GUILayout.EndHorizontal(); } GUILayout.EndScrollView(); AcceptDrops(); Repaint(); }
public void DoAvatarPreview(Rect rect, GUIStyle background) { Init(); Rect choserRect = new Rect(rect.xMax - 16, rect.yMax - 16, 16, 16); if (EditorGUI.DropdownButton(choserRect, GUIContent.none, FocusType.Passive, GUIStyle.none)) { GenericMenu menu = new GenericMenu(); menu.AddItem(EditorGUIUtility.TrTextContent("Auto"), false, SetPreviewAvatarOption, PreviewPopupOptions.Auto); menu.AddItem(EditorGUIUtility.TrTextContent("Unity Model"), false, SetPreviewAvatarOption, PreviewPopupOptions.DefaultModel); menu.AddItem(EditorGUIUtility.TrTextContent("Other..."), false, SetPreviewAvatarOption, PreviewPopupOptions.Other); menu.ShowAsContext(); } Rect previewRect = rect; previewRect.yMin += kTimeControlRectHeight; previewRect.height = Mathf.Max(previewRect.height, 64f); int previewID = GUIUtility.GetControlID(m_PreviewHint, FocusType.Passive, previewRect); Event evt = Event.current; EventType type = evt.GetTypeForControl(previewID); if (type == EventType.Repaint && m_IsValid) { DoRenderPreview(previewRect, background); previewUtility.EndAndDrawPreview(previewRect); } AvatarTimeControlGUI(rect); GUI.DrawTexture(choserRect, s_Styles.avatarIcon.image); int previewSceneID = GUIUtility.GetControlID(m_PreviewSceneHint, FocusType.Passive); type = evt.GetTypeForControl(previewSceneID); DoAvatarPreviewDrag(type); HandleViewTool(evt, type, previewSceneID, previewRect); DoAvatarPreviewFrame(evt, type, previewRect); if (!m_IsValid) { Rect warningRect = previewRect; warningRect.yMax -= warningRect.height / 2 - 16; EditorGUI.DropShadowLabel( warningRect, "No model is available for preview.\nPlease drag a model into this Preview Area."); } // Check for model selected from ObjectSelector if (evt.type == EventType.ExecuteCommand) { string commandName = evt.commandName; if (commandName == ObjectSelector.ObjectSelectorUpdatedCommand && ObjectSelector.get.objectSelectorID == m_ModelSelectorId) { SetPreview(ObjectSelector.GetCurrentObject() as GameObject); evt.Use(); } } // Apply the current cursor if (evt.type == EventType.Repaint) { EditorGUIUtility.AddCursorRect(previewRect, currentCursor); } }
// shared by compute shader inspector too internal static void ShaderErrorListUI(Object shader, ShaderMessage[] messages, ref Vector2 scrollPosition) { int n = messages.Length; GUILayout.Space(kSpace); GUILayout.Label(string.Format("Errors ({0}):", n), EditorStyles.boldLabel); int errorListID = GUIUtility.GetControlID(kErrorViewHash, FocusType.Passive); float height = Mathf.Min(n * 20f + 40f, 150f); scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUISkin.current.box, GUILayout.MinHeight(height)); EditorGUIUtility.SetIconSize(new Vector2(16.0f, 16.0f)); float lineHeight = Styles.messageStyle.CalcHeight(EditorGUIUtility.TempContent(Styles.errorIcon), 100); Event e = Event.current; for (int i = 0; i < n; ++i) { Rect r = EditorGUILayout.GetControlRect(false, lineHeight); string err = messages[i].message; string plat = messages[i].platform.ToString(); bool warn = messages[i].severity != ShaderCompilerMessageSeverity.Error; string fileName = FileUtil.GetLastPathNameComponent(messages[i].file); int line = messages[i].line; // Double click opens shader file at error line if (e.type == EventType.MouseDown && e.button == 0 && r.Contains(e.mousePosition)) { GUIUtility.keyboardControl = errorListID; if (e.clickCount == 2) { string filePath = messages[i].file; Object asset = string.IsNullOrEmpty(filePath) ? null : AssetDatabase.LoadMainAssetAtPath(filePath); // if we don't have an asset and the filePath is an absolute path, it's an error in a system // cginc - open that instead if (asset == null && System.IO.Path.IsPathRooted(filePath)) { ShaderUtil.OpenSystemShaderIncludeError(filePath, line); } else { AssetDatabase.OpenAsset(asset ?? shader, line); } GUIUtility.ExitGUI(); } e.Use(); } // Context menu, "Copy" if (e.type == EventType.ContextClick && r.Contains(e.mousePosition)) { e.Use(); var menu = new GenericMenu(); // need to copy current value to be used in delegate // (C# closures close over variables, not their values) var errorIndex = i; menu.AddItem(EditorGUIUtility.TrTextContent("Copy error text"), false, delegate { string errMsg = messages[errorIndex].message; if (!string.IsNullOrEmpty(messages[errorIndex].messageDetails)) { errMsg += '\n'; errMsg += messages[errorIndex].messageDetails; } EditorGUIUtility.systemCopyBuffer = errMsg; }); menu.ShowAsContext(); } // background if (e.type == EventType.Repaint) { if ((i & 1) == 0) { GUIStyle st = Styles.evenBackground; st.Draw(r, false, false, false, false); } } // error location on the right side Rect locRect = r; locRect.xMin = locRect.xMax; if (line > 0) { GUIContent gc; if (string.IsNullOrEmpty(fileName)) { gc = EditorGUIUtility.TempContent(line.ToString(CultureInfo.InvariantCulture)); } else { gc = EditorGUIUtility.TempContent(fileName + ":" + line.ToString(CultureInfo.InvariantCulture)); } // calculate size so we can right-align it Vector2 size = EditorStyles.miniLabel.CalcSize(gc); locRect.xMin -= size.x; GUI.Label(locRect, gc, EditorStyles.miniLabel); locRect.xMin -= 2; // ensure some minimum width so that platform field next will line up if (locRect.width < 30) { locRect.xMin = locRect.xMax - 30; } } // platform to the left of it Rect platRect = locRect; platRect.width = 0; if (plat.Length > 0) { GUIContent gc = EditorGUIUtility.TempContent(plat); // calculate size so we can right-align it Vector2 size = EditorStyles.miniLabel.CalcSize(gc); platRect.xMin -= size.x; // draw platform in dimmer color; it's often not very important information Color oldColor = GUI.contentColor; GUI.contentColor = new Color(1, 1, 1, 0.5f); GUI.Label(platRect, gc, EditorStyles.miniLabel); GUI.contentColor = oldColor; platRect.xMin -= 2; } // error message Rect msgRect = r; msgRect.xMax = platRect.xMin; GUI.Label(msgRect, EditorGUIUtility.TempContent(err, warn ? Styles.warningIcon : Styles.errorIcon), Styles.messageStyle); } EditorGUIUtility.SetIconSize(Vector2.zero); GUILayout.EndScrollView(); }
protected override void ContextClickedItem(int id) { UnityEditor.GenericMenu menu = new UnityEditor.GenericMenu(); var item = Find(id); if (CheckWaapi()) { if (CanPlay(item)) { menu.AddItem(UnityEditor.EditorGUIUtility.TrTextContent("Play \u2215 Stop _SPACE"), false, () => AkWaapiUtilities.TogglePlayEvent(item.objectType, item.objectGuid)); } else { menu.AddDisabledItem(UnityEditor.EditorGUIUtility.TrTextContent("Play \u2215 Stop _Space")); } menu.AddItem(UnityEditor.EditorGUIUtility.TrTextContent("Stop All"), false, () => AkWaapiUtilities.StopAllTransports()); menu.AddSeparator(""); if (CanRenameWithLog(item, false)) { menu.AddItem(UnityEditor.EditorGUIUtility.TrTextContent("Rename _F2"), false, () => BeginRename(item)); } else { menu.AddDisabledItem(UnityEditor.EditorGUIUtility.TrTextContent("Rename")); } if (CanDelete(item, false)) { menu.AddItem(UnityEditor.EditorGUIUtility.TrTextContent("Delete _Delete"), false, () => AkWaapiUtilities.Delete(item.objectGuid)); } else { menu.AddDisabledItem(UnityEditor.EditorGUIUtility.TrTextContent("Delete")); } menu.AddSeparator(""); if (item.objectType == WwiseObjectType.Soundbank) { menu.AddItem(UnityEditor.EditorGUIUtility.TrTextContent("Open Folder/WorkUnit #O"), false, () => AkWaapiUtilities.OpenWorkUnitInExplorer(item.objectGuid)); menu.AddItem(UnityEditor.EditorGUIUtility.TrTextContent("Open Folder/SoundBank "), false, () => AkWaapiUtilities.OpenSoundBankInExplorer(item.objectGuid)); } else { menu.AddItem(UnityEditor.EditorGUIUtility.TrTextContent("Open Containing Folder #O"), false, () => AkWaapiUtilities.OpenWorkUnitInExplorer(item.objectGuid)); } menu.AddItem(UnityEditor.EditorGUIUtility.TrTextContent("Find in Project Explorer #F"), false, () => m_dataSource.SelectObjectInAuthoring(item.objectGuid)); } else { if (AkWwiseProjectInfo.GetData().currentDataSource == AkWwiseProjectInfo.DataSourceType.WwiseAuthoring) { menu.AddItem(UnityEditor.EditorGUIUtility.TrTextContent("Wwise Connection Settings"), false, OpenSettings); menu.AddSeparator(""); } menu.AddDisabledItem(UnityEditor.EditorGUIUtility.TrTextContent("Play \u2215 Stop")); menu.AddDisabledItem(UnityEditor.EditorGUIUtility.TrTextContent("Stop all")); menu.AddSeparator(""); menu.AddDisabledItem(UnityEditor.EditorGUIUtility.TrTextContent("Rename")); menu.AddDisabledItem(UnityEditor.EditorGUIUtility.TrTextContent("Delete")); menu.AddSeparator(""); menu.AddDisabledItem(UnityEditor.EditorGUIUtility.TrTextContent("Open Containing Folder")); menu.AddDisabledItem(UnityEditor.EditorGUIUtility.TrTextContent("Find in Project Explorer")); } menu.AddItem(UnityEditor.EditorGUIUtility.TrTextContent("Find References in Scene #R"), false, () => FindReferencesInScene(item)); menu.ShowAsContext(); }
public override void Go() { base.Go(); var genericMenu = new GenericMenu(); CreateMenuItems(genericMenu); genericMenu.ShowAsContext(); }
/// <summary> /// Draw the property pop-up. /// </summary> public override void OnGUI (SerializedNodeProperty property, ActionNode node, GUIContent guiContent) { // String if (property.propertyType == NodePropertyType.String) { var rect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.popup); var id = GUIUtility.GetControlID(FocusType.Passive); var popupRect = EditorGUI.PrefixLabel(rect, id, guiContent); var popupName = property.value as string ?? string.Empty; var propertyOrField = node as PropertyOrField; var oldGUIColor = GUI.color; if (propertyOrField.propertyType == null) GUI.color = Color.red; if (GUI.Button(popupRect, string.IsNullOrEmpty(popupName) ? "None" : popupName, EditorStyles.popup)) { var isSetProperty = propertyOrField is SetProperty; var members = FieldUtility.GetPublicMembers(propertyOrField.targetObject.ObjectType, null, false, isSetProperty, !isSetProperty); var menu = new GenericMenu(); // Add none menu.AddItem(new GUIContent("None"), string.IsNullOrEmpty(popupName), delegate () {property.value = string.Empty;}); // Add members for (int i = 0; i < members.Length; i++) { var memberName = members[i].Name; menu.AddItem(new GUIContent(memberName), popupName == memberName, delegate () {property.value = memberName;}); } menu.ShowAsContext(); } GUI.color = oldGUIColor; } // Not String else EditorGUILayout.LabelField(guiContent, new GUIContent("Use UnityObjectProperty with string.")); }
private void AddDropdown(Rect buttonRect, ReorderableList l) { var menu = new GenericMenu(); foreach (string levelName in _listLevelName) menu.AddItem(new GUIContent(levelName), false, AddDropdownItem, levelName); menu.ShowAsContext(); }