예제 #1
0
 static ReorderableListControl()
 {
     ReorderableListControl.s_AnchorIndex = -1;
     ReorderableListControl.s_TargetIndex = -1;
     ReorderableListControl.s_AutoFocusControlID = 0;
     ReorderableListControl.s_AutoFocusIndex = -1;
     ReorderableListControl.s_ContainerHeightCache = new Dictionary<int, float>();
     ReorderableListControl.commandMoveToTop = new GUIContent("Move to Top");
     ReorderableListControl.commandMoveToBottom = new GUIContent("Move to Bottom");
     ReorderableListControl.commandInsertAbove = new GUIContent("Insert Above");
     ReorderableListControl.commandInsertBelow = new GUIContent("Insert Below");
     ReorderableListControl.commandDuplicate = new GUIContent("Duplicate");
     ReorderableListControl.commandRemove = new GUIContent("Remove");
     ReorderableListControl.commandClearAll = new GUIContent("Clear All");
     ReorderableListControl.defaultContextHandler = new GenericMenu.MenuFunction2(ReorderableListControl.DefaultContextMenuHandler);
     ReorderableListControl.s_CurrentItemIndex = new Stack<int>();
     ReorderableListControl.s_CurrentItemIndex.Push(-1);
     if (EditorGUIUtility.isProSkin)
     {
         ReorderableListControl.AnchorBackgroundColor = new Color(0.333333343f, 0.333333343f, 0.333333343f, 0.85f);
         ReorderableListControl.TargetBackgroundColor = new Color(0f, 0f, 0f, 0.5f);
     }
     else
     {
         ReorderableListControl.AnchorBackgroundColor = new Color(0.882352948f, 0.882352948f, 0.882352948f, 0.85f);
         ReorderableListControl.TargetBackgroundColor = new Color(0f, 0f, 0f, 0.5f);
     }
     ReorderableListControl.s_RemoveButtonNormalContent = new GUIContent(ReorderableListResources.texRemoveButton);
     ReorderableListControl.s_RemoveButtonActiveContent = new GUIContent(ReorderableListResources.texRemoveButtonActive);
 }
예제 #2
0
			public MenuItem(GUIContent _content, bool _separator, bool _on, GenericMenu.MenuFunction2 _func, object _userData)
			{
				this.content = _content;
				this.separator = _separator;
				this.on = _on;
				this.func2 = _func;
				this.userData = _userData;
			}
        private void CreatePopupMenu(string title, GUIContent content, EditorSettingsInspector.PopupElement[] elements, int selectedIndex, GenericMenu.MenuFunction2 func)
        {
            Rect rect = GUILayoutUtility.GetRect(content, EditorStyles.popup);

            rect = EditorGUI.PrefixLabel(rect, 0, new GUIContent(title));
            if (EditorGUI.DropdownButton(rect, content, FocusType.Passive, EditorStyles.popup))
            {
                this.DoPopup(rect, elements, selectedIndex, func);
            }
        }
    void BoneSelectorContextMenu(string current, ExposedList <Bone> bones, string topValue, GenericMenu.MenuFunction2 callback)
    {
        GenericMenu menu = new GenericMenu();

        if (topValue != "")
        {
            menu.AddItem(new GUIContent(topValue), current == topValue, callback, null);
        }

        for (int i = 0; i < bones.Count; i++)
        {
            menu.AddItem(new GUIContent(bones.Items[i].Data.Name), bones.Items[i].Data.Name == current, callback, bones.Items[i]);
        }

        menu.ShowAsContext();
    }
예제 #5
0
        /// <summary>
        /// Shows the add menu for the specified type
        /// </summary>
        /// <param name="type">The type that should be shown.</param>
        /// <param name="condition">Delegate which allows for custom conditions to be checked before the type is added.</param>
        /// <param name="addCallback">The callback when a type is selected from the menu.</param>
        public static void AddObjectType(Type type, Func <Type, bool> condition, GenericMenu.MenuFunction2 addCallback)
        {
            var typeWithCondition = new TypeWithCondition()
            {
                Type = type, Condition = condition
            };

            if (!s_ObjectTypes.TryGetValue(typeWithCondition, out var typeList))
            {
                typeList = new List <Type>();

                // Search through all of the assemblies to find any types that derive from specified type.
                var assemblies = AppDomain.CurrentDomain.GetAssemblies();
                for (int i = 0; i < assemblies.Length; ++i)
                {
                    var assemblyTypes = assemblies[i].GetTypes();
                    for (int j = 0; j < assemblyTypes.Length; ++j)
                    {
                        var assemblyType = assemblyTypes[j];

                        // Must derive from specified type.
                        if (!type.IsAssignableFrom(assemblyType))
                        {
                            continue;
                        }

                        // Ignore abstract classes.
                        if (assemblyType.IsAbstract)
                        {
                            continue;
                        }

                        //Check condition.
                        if (condition != null)
                        {
                            if (condition.Invoke(assemblyType) == false)
                            {
                                continue;
                            }
                        }

                        typeList.Add(assemblyType);
                    }
                }
                s_ObjectTypes.Add(typeWithCondition, typeList);
            }

            if (typeList == null || typeList.Count == 0)
            {
                return;
            }

            // All of the types have been retrieved. Show the menu.
            var addMenu = new GenericMenu();

            for (int i = 0; i < typeList.Count; ++i)
            {
                addMenu.AddItem(new GUIContent(Shared.Editor.Utility.EditorUtility.SplitCamelCase(typeList[i].Name)), false, addCallback, typeList[i]);
            }
            addMenu.ShowAsContext();
        }
 static bool ButtonWithDropdownList(GUIContent content, string[] buttonNames, GenericMenu.MenuFunction2 callback, params GUILayoutOption[] options)
 {
     return((bool)k_EditorGUI_ButtonWithDropdownList.Invoke(null, new object[] { content, buttonNames, callback, options }));
 }
예제 #7
0
        public static void Flags(Rect position, FlagsOption[] options, Action <FlagsOption, SerializedProperty> onSelected, GUIContent label = null, SerializedProperty property = null)
        {
            label = label ?? property.ToGUIContent();
            int        selectedCount = options.Count(option => option.IsSelected);
            bool       nothing       = selectedCount == 0;
            bool       everything    = selectedCount == options.Length;
            GUIContent popupName;

            position = EditorGUI.PrefixLabel(position, label);

            if (nothing)
            {
                popupName = "Nothing".ToGUIContent();
            }
            else if (everything)
            {
                popupName = "Everything".ToGUIContent();
            }
            else
            {
                var name = "";

                foreach (var option in options)
                {
                    if (option.IsSelected)
                    {
                        if (string.IsNullOrEmpty(name))
                        {
                            name = option.Label.text;
                        }
                        else
                        {
                            name += " | " + option.Label.text;
                        }
                    }
                }

                if (selectedCount > 1 && name.GetWidth(EditorStyles.miniFont) > position.width)
                {
                    popupName = string.Format("Mixed ({0}) ...", selectedCount).ToGUIContent();
                }
                else
                {
                    popupName = name.ToGUIContent();
                }
            }

            int indent = EditorGUI.indentLevel;

            EditorGUI.indentLevel = 0;
            GenericMenu.MenuFunction2 callback = data => onSelected((FlagsOption)data, property);

            if (GUI.Button(position, GUIContent.none, new GUIStyle()))
            {
                var menu = new GenericMenu();

                menu.AddItem(FlagsOption.GetNothing(nothing), callback);
                menu.AddItem(FlagsOption.GetEverything(everything), callback);

                for (int i = 0; i < options.Length; i++)
                {
                    var option = options[i];
                    menu.AddItem(option.Label, option.IsSelected, callback, option);
                }

                menu.DropDown(position);
            }

            EditorGUI.LabelField(position, popupName, EditorStyles.popup);
            EditorGUI.indentLevel = indent;
        }
예제 #8
0
        //...
        void OnGUI()
        {
            GUI.skin.label.richText = true;
            EditorGUILayout.HelpBox("Here you can specify frequently used types for your project and 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. To add types in the list quicker, you can also Drag&Drop an object, or a Script file in this editor window.\n\nIf you save a preset in your 'Editor Default Resources/" + TypePrefs.SYNC_FILE_NAME + "' it will automatically sync with the list. Useful when working with others on source control.", MessageType.Info);

            if (GUILayout.Button("Add New Type", EditorStyles.miniButton))
            {
                GenericMenu.MenuFunction2 Selected = delegate(object o)
                {
                    if (o is System.Type)
                    {
                        AddType((System.Type)o);
                    }
                    if (o is string)     //namespace
                    {
                        foreach (var type in alltypes)
                        {
                            if (type.Namespace == (string)o)
                            {
                                AddType(type);
                            }
                        }
                    }
                };

                var menu       = new GenericMenu();
                var namespaces = new List <string>();
                menu.AddItem(new GUIContent("Classes/System/Object"), false, Selected, typeof(object));
                foreach (var t in alltypes)
                {
                    var a            = (string.IsNullOrEmpty(t.Namespace) ? "No Namespace/" : t.Namespace.Replace(".", "/") + "/") + t.FriendlyName();
                    var b            = string.IsNullOrEmpty(t.Namespace) ? string.Empty : " (" + t.Namespace + ")";
                    var friendlyName = a + b;
                    var category     = "Classes/";
                    if (t.IsValueType)
                    {
                        category = "Structs/";
                    }
                    if (t.IsInterface)
                    {
                        category = "Interfaces/";
                    }
                    if (t.IsEnum)
                    {
                        category = "Enumerations/";
                    }
                    menu.AddItem(new GUIContent(category + friendlyName), typeList.Contains(t), Selected, t);
                    if (t.Namespace != null && !namespaces.Contains(t.Namespace))
                    {
                        namespaces.Add(t.Namespace);
                    }
                }

                menu.AddSeparator("/");
                foreach (var ns in namespaces)
                {
                    var path = "Whole Namespaces/" + ns.Replace(".", "/") + "/Add " + ns;
                    menu.AddItem(new GUIContent(path), false, Selected, ns);
                }

                menu.ShowAsBrowser("Add Preferred Type");
            }


            if (GUILayout.Button("Generate AOTClasses.cs and link.xml Files", EditorStyles.miniButton))
            {
                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, TypePrefs.GetPreferedTypesList(true).ToArray());
                    }
                }

                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, TypePrefs.GetPreferedTypesList().ToArray());
                    }
                }

                AssetDatabase.Refresh();
            }

            GUILayout.BeginHorizontal();

            if (GUILayout.Button("Reset Defaults", EditorStyles.miniButtonLeft))
            {
                if (EditorUtility.DisplayDialog("Reset Preferred Types", "Are you sure?", "Yes", "NO!"))
                {
                    TypePrefs.ResetTypeConfiguration();
                    typeList = TypePrefs.GetPreferedTypesList();
                    Save();
                }
            }

            if (GUILayout.Button("Save Preset", EditorStyles.miniButtonMid))
            {
                var path = EditorUtility.SaveFilePanelInProject("Save Types Preset", "PreferredTypes", "typePrefs", "");
                if (!string.IsNullOrEmpty(path))
                {
                    System.IO.File.WriteAllText(path, JSONSerializer.Serialize(typeof(List <System.Type>), typeList, null, true));
                    AssetDatabase.Refresh();
                }
            }

            if (GUILayout.Button("Load Preset", EditorStyles.miniButtonRight))
            {
                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();
            GUILayout.Space(5);
            var syncPath = TypePrefs.SyncFilePath();

            EditorGUILayout.HelpBox(syncPath != null ? "List synced with file: " + syncPath.Replace(Application.dataPath, ".../Assets") : "No sync file found in '.../Assets/Editor Default Resources'. Types are currently saved in Unity EditorPrefs only.", MessageType.None);
            GUILayout.Space(5);

            scrollPos = GUILayout.BeginScrollView(scrollPos);
            for (int i = 0; i < typeList.Count; i++)
            {
                if (EditorGUIUtility.isProSkin)
                {
                    GUI.color = Color.black.WithAlpha(i % 2 == 0 ? 0.3f : 0);
                }
                if (!EditorGUIUtility.isProSkin)
                {
                    GUI.color = Color.white.WithAlpha(i % 2 == 0 ? 0.3f : 0);
                }
                GUILayout.BeginHorizontal("box");
                GUI.color = Color.white;
                var type = typeList[i];
                if (type == null)
                {
                    GUILayout.Label("MISSING TYPE", GUILayout.Width(300));
                    GUILayout.Label("---");
                }
                else
                {
                    var name = type.FriendlyName();
                    var icon = TypePrefs.GetTypeIcon(type);
                    GUILayout.Label(icon, GUILayout.Width(16), GUILayout.Height(16));
                    GUILayout.Label(name, GUILayout.Width(300));
                    GUILayout.Label(type.Namespace);
                }
                if (GUILayout.Button("X", GUILayout.Width(18)))
                {
                    RemoveType(type);
                }
                GUILayout.EndHorizontal();
            }
            GUILayout.EndScrollView();

            AcceptDrops();
            Repaint();
        }
        // Shows an active button and a triangle button on the right, which expands the dropdown list
        // Returns true if button was activated, returns false if the the dropdown button was activated or the button was not clicked.
        internal static bool ButtonWithDropdownList(string buttonName, string[] buttonNames, GenericMenu.MenuFunction2 callback, params GUILayoutOption[] options)
        {
            var content = EditorGUIUtility.TempContent(buttonName);

            return(ButtonWithDropdownList(content, buttonNames, callback, options));
        }
예제 #10
0
        internal static void DoPopup(Rect popupRect, PopupElement[] elements, int selectedIndex, GenericMenu.MenuFunction2 func)
        {
            GenericMenu menu = new GenericMenu();

            for (int i = 0; i < elements.Length; i++)
            {
                var element = elements[i];
                menu.AddItem(element.content, i == selectedIndex, func, i);
            }
            menu.DropDown(popupRect);
        }
        ///Get a GenericMenu for method or property get/set methods selection in a type
        static GenericMenu Internal_GetMethodSelectionMenu(BindingFlags flags, Type type, Type returnType, Type acceptedParamsType, System.Action <MethodInfo> callback, int maxParameters, bool propertiesOnly, bool excludeVoid = false, GenericMenu menu = null, string subMenu = null)
        {
            if (menu == null)
            {
                menu = new GenericMenu();
            }

            if (subMenu != null)
            {
                subMenu = subMenu + "/";
            }

            GenericMenu.MenuFunction2 Selected = delegate(object selectedMethod){
                callback((MethodInfo)selectedMethod);
            };

            var itemAdded = false;
            var more      = false;

            foreach (var method in type.GetMethods(flags))
            {
                if (propertiesOnly != method.IsSpecialName)
                {
                    continue;
                }

                if (method.IsGenericMethod)
                {
                    continue;
                }

                if (!returnType.IsAssignableFrom(method.ReturnType))
                {
                    continue;
                }

                if (method.ReturnType == typeof(void) && excludeVoid)
                {
                    continue;
                }

                var parameters = method.GetParameters();
                if (parameters.Length > maxParameters && maxParameters != -1)
                {
                    continue;
                }

                if (parameters.Length > 0)
                {
                    if (parameters.Any(param => !acceptedParamsType.IsAssignableFrom(param.ParameterType)))
                    {
                        continue;
                    }
                }


                MemberInfo member = method;
                if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
                {
                    member = method.DeclaringType.GetProperty(method.Name.Replace("get_", "").Replace("set_", ""));
                }
                if (member != null && member.GetCustomAttributes(typeof(System.ObsoleteAttribute), true).FirstOrDefault() != null)
                {
                    continue;
                }

                if (method.DeclaringType != type)
                {
                    more = true;
                }

                var category    = more? subMenu + type.FriendlyName() + "/More" : subMenu + type.FriendlyName();
                var finalMethod = method.GetBaseDefinition();
                menu.AddItem(new GUIContent(category + "/" + finalMethod.SignatureName()), false, Selected, finalMethod);
                itemAdded = true;
            }

            if (!itemAdded)
            {
                menu.AddDisabledItem(new GUIContent(subMenu + type.FriendlyName()));
            }

            return(menu);
        }
예제 #12
0
 private static void CreatePopupMenu(string title, PopupElement[] elements, int selectedIndex, GenericMenu.MenuFunction2 func)
 {
     CreatePopupMenu(title, elements[selectedIndex].content, elements, selectedIndex, func);
 }
예제 #13
0
        internal static void CreatePopupMenu(string title, GUIContent content, PopupElement[] elements, int selectedIndex, GenericMenu.MenuFunction2 func)
        {
            var popupRect = GUILayoutUtility.GetRect(content, EditorStyles.popup);

            popupRect = EditorGUI.PrefixLabel(popupRect, 0, new GUIContent(title));
            if (EditorGUI.DropdownButton(popupRect, content, FocusType.Passive, EditorStyles.popup))
            {
                DoPopup(popupRect, elements, selectedIndex, func);
            }
        }
예제 #14
0
 protected void AddAchieveItem(string menuName, GenericMenu.MenuFunction2 function, object userData, bool able)
 {
     m_MenuItems.Add(menuName, new MenuItem(menuName, function, userData, () => able));
 }
예제 #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="position"></param>
        /// <param name="property"></param>
        /// <param name="label"></param>
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            var e = Event.current;

            if (property.propertyType == SerializedPropertyType.ObjectReference)
            {
                if ((e.type == EventType.DragPerform ||
                     e.type == EventType.DragExited ||
                     e.type == EventType.DragUpdated ||
                     e.type == EventType.Repaint) &&
                    position.Contains(e.mousePosition) &&
                    e.shift)
                {
                    if (DragAndDrop.objectReferences != null)
                    {
                        this._m_list.Clear();
                        foreach (var o in DragAndDrop.objectReferences)
                        {
                            this._m_list.Add(o);
                            var go = o as GameObject;
                            if (go == null && o is Component)
                            {
                                go = ((Component)o).gameObject;
                                this._m_list.Add(go);
                            }

                            if (go != null)
                            {
                                foreach (var c in go.GetComponents <Component>())
                                {
                                    if (c != o)
                                    {
                                        this._m_list.Add(c);
                                    }
                                }
                            }
                        }

                        var field_info = property.GetPropertyReferenceType();
                        if (field_info != null)
                        {
                            var type = field_info.FieldType;
                            for (var i = this._m_list.Count - 1; i >= 0; i--)
                            {
                                if (this._m_list[i] == null || !type.IsAssignableFrom(this._m_list[i].GetType()))
                                {
                                    this._m_list.RemoveAt(i);
                                }
                            }
                        }

                        var att = this.attribute as ObjectDropdownFilterAttribute;
                        if (att != null)
                        {
                            var type = att._FilterType;
                            for (var i = this._m_list.Count - 1; i >= 0; i--)
                            {
                                if (!type.IsAssignableFrom(this._m_list[i].GetType()))
                                {
                                    this._m_list.RemoveAt(i);
                                }
                            }
                        }

                        if (this._m_list.Count == 0)
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
                        }
                        else
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                            if (e.type == EventType.DragPerform)
                            {
                                var gm = new GenericMenu();
                                GenericMenu.MenuFunction2 func = o => {
                                    property.objectReferenceValue = (Object)o;
                                    property.serializedObject.ApplyModifiedProperties();
                                };
                                foreach (var item in this._m_list)
                                {
                                    gm.AddItem(new GUIContent(item.name + "(" + item.GetType().Name + ")"), false, func, item);
                                }

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

                        this._m_list.Clear();
                    }
                }

                EditorGUI.ObjectField(position, property, label);
            }
            else
            {
                EditorGUI.PropertyField(position, property, label);
            }
        }
        internal static void CreatePopupMenu(SerializedObject obj, string title, GUIContent content, PopupElement[] elements, int selectedIndex, GenericMenu.MenuFunction2 func)
        {
            var popupRect = GUILayoutUtility.GetRect(content, EditorStyles.popup);

            popupRect = EditorGUI.PrefixLabel(popupRect, 0, new GUIContent(title));
            if (EditorGUI.DropdownButton(popupRect, content, FocusType.Passive, EditorStyles.popup))
            {
                DoPopup(popupRect, elements, selectedIndex, data =>
                {
                    func(data);
                    obj?.ApplyModifiedProperties();
                });
            }
        }
        private void DoPopup(Rect popupRect, EditorSettingsInspector.PopupElement[] elements, int selectedIndex, GenericMenu.MenuFunction2 func)
        {
            GenericMenu genericMenu = new GenericMenu();

            for (int i = 0; i < elements.Length; i++)
            {
                EditorSettingsInspector.PopupElement popupElement = elements[i];
                if (popupElement.Enabled)
                {
                    genericMenu.AddItem(popupElement.content, i == selectedIndex, func, i);
                }
                else
                {
                    genericMenu.AddDisabledItem(popupElement.content);
                }
            }
            genericMenu.DropDown(popupRect);
        }
        /// !* Providing an open GenericTypeDefinition for 'baseType', wraps the Preferred Types wihin the 1st Generic Argument of that Definition *!
        public static GenericMenu GetPreferedTypesSelectionMenu(Type baseType, Action <Type> callback, GenericMenu menu = null, string subCategory = null, bool showAddTypeOption = false)
        {
            if (menu == null)
            {
                menu = new GenericMenu();
            }

            if (subCategory != null)
            {
                subCategory = subCategory + "/";
            }

            var constrainType     = baseType;
            var isGeneric         = baseType.IsGenericTypeDefinition && baseType.GetGenericArguments().Length == 1;
            var genericDefinition = isGeneric? baseType : null;

            if (isGeneric)
            {
                var arg1       = genericDefinition.GetGenericArguments().First();
                var constrains = arg1.GetGenericParameterConstraints();
                constrainType = constrains.Length == 0? typeof(object) : constrains.First();
            }

            GenericMenu.MenuFunction2 Selected = delegate(object t){
                callback((Type)t);
            };

            var listTypes = new Dictionary <Type, string>();
            var dictTypes = new Dictionary <Type, string>();

            foreach (var t in UserTypePrefs.GetPreferedTypesList(constrainType, true))
            {
                var nsString    = t.NamespaceToPath() + "/";
                var finalType   = isGeneric? genericDefinition.MakeGenericType(t) : t;
                var finalString = nsString + finalType.FriendlyName();
                menu.AddItem(new GUIContent(subCategory + finalString), false, Selected, finalType);

                var listType      = typeof(List <>).MakeGenericType(t);
                var finalListType = isGeneric? genericDefinition.MakeGenericType(listType) : listType;
                if (constrainType.IsAssignableFrom(finalListType))
                {
                    listTypes[finalListType] = nsString;
                }

                var dictType      = typeof(Dictionary <,>).MakeGenericType(typeof(string), t);
                var finalDictType = isGeneric? genericDefinition.MakeGenericType(dictType) : dictType;
                if (constrainType.IsAssignableFrom(finalDictType))
                {
                    dictTypes[finalDictType] = nsString;
                }
            }

            foreach (var tPair in listTypes)
            {
                menu.AddItem(new GUIContent(subCategory + UserTypePrefs.LIST_MENU_STRING + tPair.Value + tPair.Key.FriendlyName()), false, Selected, tPair.Key);
            }

            foreach (var tPair in dictTypes)
            {
                menu.AddItem(new GUIContent(subCategory + UserTypePrefs.DICT_MENU_STRING + tPair.Value + tPair.Key.FriendlyName()), false, Selected, tPair.Key);
            }

            if (showAddTypeOption)
            {
                menu.AddItem(new GUIContent(subCategory + "Add Type..."), false, () => { PreferedTypesEditorWindow.ShowWindow(); });
            }

            return(menu);
        }
예제 #19
0
        public static void DropdownMultiple
        (
            Vector2 position,
            MultipleCallback callback,
            IEnumerable <DropdownOption <T> > options,
            IEnumerable <T> selectedOptions,
            bool hasMultipleDifferentValues
        )
        {
            selectedOptions = SanitizeMultipleOptions(options, selectedOptions);

            bool hasOptions = options != null && options.Any();

            GenericMenu menu = new GenericMenu();

            GenericMenu.MenuFunction2 switchCallback = (o) =>
            {
                GUI.changed = true;

                var switchOption = (T)o;

                var newSelectedOptions = selectedOptions.ToList();

                if (newSelectedOptions.Contains(switchOption))
                {
                    newSelectedOptions.Remove(switchOption);
                }
                else
                {
                    newSelectedOptions.Add(switchOption);
                }

                callback(newSelectedOptions);
            };

            GenericMenu.MenuFunction nothingCallback = () =>
            {
                GUI.changed = true;
                callback(Enumerable.Empty <T>());
            };

            GenericMenu.MenuFunction everythingCallback = () =>
            {
                GUI.changed = true;
                callback(options.Select((o) => o.value));
            };

            menu.AddItem(new GUIContent("Nothing"), !hasMultipleDifferentValues && !selectedOptions.Any(), nothingCallback);
            menu.AddItem(new GUIContent("Everything"), !hasMultipleDifferentValues && selectedOptions.Count() == options.Count() && Enumerable.SequenceEqual(selectedOptions.OrderBy(t => t), options.Select(o => o.value).OrderBy(t => t)), everythingCallback);

            if (hasOptions)
            {
                menu.AddSeparator("");                 // Not in Unity default, but pretty

                foreach (var option in options)
                {
                    bool on = !hasMultipleDifferentValues && (selectedOptions.Any(selectedOption => EqualityComparer <T> .Default.Equals(selectedOption, option.value)));

                    menu.AddItem(new GUIContent(option.label), on, switchCallback, option.value);
                }
            }

            menu.DropDown(new Rect(position, Vector2.zero));
        }
예제 #20
0
 /// <summary>
 /// Adds an item to the menu
 /// </summary>
 /// <param name="content">The content to display</param>
 /// <param name="showTick">Should the item show a check in front of it</param>
 /// <param name="func">The function to call when this item is clicked</param>
 /// <param name="data">The data to pass to the function</param>
 public GenericMenuBuilder AddItem(GUIContent content, bool showTick, GenericMenu.MenuFunction2 func, object data)
 {
     Menu.AddItem(content, showTick, func, data);
     return(this);
 }
 public MenuItemInfo(GUIContent c, bool sep, bool slc, GenericMenu.MenuFunction f1, GenericMenu.MenuFunction2 f2, object o)
 {
     content   = c;
     separator = sep;
     selected  = slc;
     func      = f1;
     func2     = f2;
     userData  = o;
 }
예제 #22
0
        public static bool Slider(GUIContent label, ref float value, float displayScale, float displayExponent, string unit, float leftValue, float rightValue, AudioMixerController controller, AudioParameterPath path, params GUILayoutOption[] options)
        {
            EditorGUI.BeginChangeCheck();
            float  fieldWidth = EditorGUIUtility.fieldWidth;
            string kFloatFieldFormatString = EditorGUI.kFloatFieldFormatString;
            bool   flag = controller.ContainsExposedParameter(path.parameter);

            EditorGUIUtility.fieldWidth       = 70f;
            EditorGUI.kFloatFieldFormatString = "F2";
            EditorGUI.s_UnitString            = unit;
            GUIContent label2 = label;

            if (flag)
            {
                label2 = GUIContent.Temp(label.text + " ➔", label.tooltip);
            }
            float num = value * displayScale;

            num = EditorGUILayout.PowerSlider(label2, num, leftValue * displayScale, rightValue * displayScale, displayExponent, options);
            EditorGUI.s_UnitString            = null;
            EditorGUI.kFloatFieldFormatString = kFloatFieldFormatString;
            EditorGUIUtility.fieldWidth       = fieldWidth;
            if (Event.current.type == EventType.ContextClick)
            {
                if (GUILayoutUtility.topLevel.GetLast().Contains(Event.current.mousePosition))
                {
                    Event.current.Use();
                    GenericMenu genericMenu = new GenericMenu();
                    if (!flag)
                    {
                        GenericMenu arg_11E_0 = genericMenu;
                        GUIContent  arg_11E_1 = new GUIContent("Expose '" + path.ResolveStringPath(false) + "' to script");
                        bool        arg_11E_2 = false;
                        if (AudioMixerEffectGUI.< > f__mg$cache0 == null)
                        {
                            AudioMixerEffectGUI.< > f__mg$cache0 = new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ExposePopupCallback);
                        }
                        arg_11E_0.AddItem(arg_11E_1, arg_11E_2, AudioMixerEffectGUI.< > f__mg$cache0, new AudioMixerEffectGUI.ExposedParamContext(controller, path));
                    }
                    else
                    {
                        GenericMenu arg_15B_0 = genericMenu;
                        GUIContent  arg_15B_1 = new GUIContent("Unexpose");
                        bool        arg_15B_2 = false;
                        if (AudioMixerEffectGUI.< > f__mg$cache1 == null)
                        {
                            AudioMixerEffectGUI.< > f__mg$cache1 = new GenericMenu.MenuFunction2(AudioMixerEffectGUI.UnexposePopupCallback);
                        }
                        arg_15B_0.AddItem(arg_15B_1, arg_15B_2, AudioMixerEffectGUI.< > f__mg$cache1, new AudioMixerEffectGUI.ExposedParamContext(controller, path));
                    }
                    ParameterTransitionType parameterTransitionType;
                    bool transitionTypeOverride = controller.TargetSnapshot.GetTransitionTypeOverride(path.parameter, out parameterTransitionType);
                    genericMenu.AddSeparator(string.Empty);
                    GenericMenu arg_1C0_0 = genericMenu;
                    GUIContent  arg_1C0_1 = new GUIContent("Linear Snapshot Transition");
                    bool        arg_1C0_2 = parameterTransitionType == ParameterTransitionType.Lerp;
                    if (AudioMixerEffectGUI.< > f__mg$cache2 == null)
                    {
                        AudioMixerEffectGUI.< > f__mg$cache2 = new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback);
                    }
                    arg_1C0_0.AddItem(arg_1C0_1, arg_1C0_2, AudioMixerEffectGUI.< > f__mg$cache2, new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Lerp));
                    GenericMenu arg_202_0 = genericMenu;
                    GUIContent  arg_202_1 = new GUIContent("Smoothstep Snapshot Transition");
                    bool        arg_202_2 = parameterTransitionType == ParameterTransitionType.Smoothstep;
                    if (AudioMixerEffectGUI.< > f__mg$cache3 == null)
                    {
                        AudioMixerEffectGUI.< > f__mg$cache3 = new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback);
                    }
                    arg_202_0.AddItem(arg_202_1, arg_202_2, AudioMixerEffectGUI.< > f__mg$cache3, new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Smoothstep));
                    GenericMenu arg_244_0 = genericMenu;
                    GUIContent  arg_244_1 = new GUIContent("Squared Snapshot Transition");
                    bool        arg_244_2 = parameterTransitionType == ParameterTransitionType.Squared;
                    if (AudioMixerEffectGUI.< > f__mg$cache4 == null)
                    {
                        AudioMixerEffectGUI.< > f__mg$cache4 = new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback);
                    }
                    arg_244_0.AddItem(arg_244_1, arg_244_2, AudioMixerEffectGUI.< > f__mg$cache4, new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Squared));
                    GenericMenu arg_286_0 = genericMenu;
                    GUIContent  arg_286_1 = new GUIContent("SquareRoot Snapshot Transition");
                    bool        arg_286_2 = parameterTransitionType == ParameterTransitionType.SquareRoot;
                    if (AudioMixerEffectGUI.< > f__mg$cache5 == null)
                    {
                        AudioMixerEffectGUI.< > f__mg$cache5 = new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback);
                    }
                    arg_286_0.AddItem(arg_286_1, arg_286_2, AudioMixerEffectGUI.< > f__mg$cache5, new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.SquareRoot));
                    GenericMenu arg_2C8_0 = genericMenu;
                    GUIContent  arg_2C8_1 = new GUIContent("BrickwallStart Snapshot Transition");
                    bool        arg_2C8_2 = parameterTransitionType == ParameterTransitionType.BrickwallStart;
                    if (AudioMixerEffectGUI.< > f__mg$cache6 == null)
                    {
                        AudioMixerEffectGUI.< > f__mg$cache6 = new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback);
                    }
                    arg_2C8_0.AddItem(arg_2C8_1, arg_2C8_2, AudioMixerEffectGUI.< > f__mg$cache6, new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.BrickwallStart));
                    GenericMenu arg_30A_0 = genericMenu;
                    GUIContent  arg_30A_1 = new GUIContent("BrickwallEnd Snapshot Transition");
                    bool        arg_30A_2 = parameterTransitionType == ParameterTransitionType.BrickwallEnd;
                    if (AudioMixerEffectGUI.< > f__mg$cache7 == null)
                    {
                        AudioMixerEffectGUI.< > f__mg$cache7 = new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback);
                    }
                    arg_30A_0.AddItem(arg_30A_1, arg_30A_2, AudioMixerEffectGUI.< > f__mg$cache7, new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.BrickwallEnd));
                    genericMenu.AddSeparator(string.Empty);
                    genericMenu.ShowAsContext();
                }
            }
            bool result;

            if (EditorGUI.EndChangeCheck())
            {
                value  = num / displayScale;
                result = true;
            }
            else
            {
                result = false;
            }
            return(result);
        }
 public static void AddItem(this GenericMenu genericMenu, string content, bool isTicked,
                            GenericMenu.MenuFunction2 func, object userData, bool isEnabled = true)
 {
     AddItem(genericMenu, new GUIContent(content), isTicked, func, userData, isEnabled);
 }
예제 #24
0
        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), true);
                    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();
        }
        // Shows an active button and a triangle button on the right, which expands the dropdown list
        // Returns true if button was activated, returns false if the the dropdown button was activated or the button was not clicked.
        internal static bool ButtonWithDropdownList(GUIContent content, string[] buttonNames, GenericMenu.MenuFunction2 callback, params GUILayoutOption[] options)
        {
            var rect = GUILayoutUtility.GetRect(content, EditorStyles.dropDownList, options);

            var         dropDownRect         = rect;
            const float kDropDownButtonWidth = 20f;

            dropDownRect.xMin = dropDownRect.xMax - kDropDownButtonWidth;

            if (Event.current.type == EventType.MouseDown && dropDownRect.Contains(Event.current.mousePosition))
            {
                var menu = new GenericMenu();
                for (int i = 0; i != buttonNames.Length; i++)
                {
                    menu.AddItem(new GUIContent(buttonNames[i]), false, callback, i);
                }

                menu.DropDown(rect);
                Event.current.Use();

                return(false);
            }

            return(GUI.Button(rect, content, EditorStyles.dropDownList));
        }
        //...
        void OnGUI()
        {
            if (EditorGUIUtility.isProSkin)
            {
                GUI.Box(new Rect(0, 0, Screen.width, Screen.height), string.Empty, Styles.shadowedBackground);
            }

            GUI.skin.label.richText = true;
            EditorGUILayout.HelpBox("Here you can specify frequently used types for your project and 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.\nFurthermore, 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.", MessageType.Info);

            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 alltypes)
                        {
                            if (type.Namespace == (string)o)
                            {
                                AddType(type);
                            }
                        }
                    }
                };

                var menu       = new GenericMenu();
                var namespaces = new List <string>();
                menu.AddItem(new GUIContent("Classes/System/Object"), false, Selected, typeof(object));
                foreach (var t in alltypes)
                {
                    var friendlyName = (string.IsNullOrEmpty(t.Namespace) ? "No Namespace/" : t.Namespace.Replace(".", "/") + "/") + t.FriendlyName();
                    var category     = "Classes/";
                    if (t.IsValueType)
                    {
                        category = "Structs/";
                    }
                    if (t.IsInterface)
                    {
                        category = "Interfaces/";
                    }
                    if (t.IsEnum)
                    {
                        category = "Enumerations/";
                    }
                    menu.AddItem(new GUIContent(category + friendlyName), typeList.Contains(t), Selected, t);
                    if (t.Namespace != null && !namespaces.Contains(t.Namespace))
                    {
                        namespaces.Add(t.Namespace);
                    }
                }

                menu.AddSeparator("/");
                foreach (var ns in namespaces)
                {
                    var path = "Whole Namespaces/" + ns.Replace(".", "/") + "/Add " + ns;
                    menu.AddItem(new GUIContent(path), false, Selected, ns);
                }

                menu.ShowAsBrowser("Add Preferred Type");
            }


            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, TypePrefs.GetPreferedTypesList(true).ToArray());
                    }
                }

                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, TypePrefs.GetPreferedTypesList().ToArray());
                    }
                }

                AssetDatabase.Refresh();
            }

            GUILayout.BeginHorizontal();

            if (GUILayout.Button("RESET DEFAULTS"))
            {
                if (EditorUtility.DisplayDialog("Reset Preferred Types", "Are you sure?", "Yes", "NO!"))
                {
                    TypePrefs.ResetTypeConfiguration();
                    typeList = TypePrefs.GetPreferedTypesList();
                    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();
            GUILayout.Space(5);

            scrollPos = GUILayout.BeginScrollView(scrollPos);
            for (int i = 0; i < typeList.Count; i++)
            {
                GUILayout.BeginHorizontal("box");
                var type = typeList[i];
                if (type == null)
                {
                    GUILayout.Label("MISSING TYPE", GUILayout.Width(300));
                    GUILayout.Label("---");
                }
                else
                {
                    var name = type.FriendlyName();
                    var icon = TypePrefs.GetTypeIcon(type);
                    GUILayout.Label(icon, GUILayout.Width(16), GUILayout.Height(16));
                    GUILayout.Label(name, GUILayout.Width(300));
                    GUILayout.Label(type.Namespace);
                }
                if (GUILayout.Button("X", GUILayout.Width(18)))
                {
                    RemoveType(type);
                }
                GUILayout.EndHorizontal();
            }
            GUILayout.EndScrollView();

            AcceptDrops();
            Repaint();
        }
예제 #27
0
        /// <summary>
        /// Shows the add menu for the specified type
        /// </summary>
        public static void AddObjectType(Type type, bool friendlyNamespacePrefix, Array existingTypes, GenericMenu.MenuFunction2 addCallback)
        {
            if (!s_ObjectTypes.TryGetValue(type, out var typeList))
            {
                // Search through all of the assemblies to find any types that derive from specified type.
                typeList = new List <Type>();
                var assemblies = AppDomain.CurrentDomain.GetAssemblies();
                for (int i = 0; i < assemblies.Length; ++i)
                {
                    var assemblyTypes = assemblies[i].GetTypes();
                    for (int j = 0; j < assemblyTypes.Length; ++j)
                    {
                        // Must derive from specified type.
                        if (!type.IsAssignableFrom(assemblyTypes[j]))
                        {
                            continue;
                        }

                        // Ignore abstract classes.
                        if (assemblyTypes[j].IsAbstract)
                        {
                            continue;
                        }

                        // Ability types should not show ItemAbilities.
                        if (type == typeof(Ability) && typeof(ItemAbility).IsAssignableFrom(assemblyTypes[j]))
                        {
                            continue;
                        }

                        typeList.Add(assemblyTypes[j]);
                    }
                }
                s_ObjectTypes.Add(type, typeList);
            }

            var addMenu = new GenericMenu();

            for (int i = 0; i < typeList.Count; ++i)
            {
                // Do not show already added types.
                var addType = true;
                if (!CanAddMultipleTypes(typeList[i]) && existingTypes != null)
                {
                    for (int j = 0; j < existingTypes.Length; ++j)
                    {
                        if (existingTypes.GetValue(j).GetType() == typeList[i])
                        {
                            addType = false;
                            break;
                        }
                    }
                }
                if (!addType)
                {
                    continue;
                }

                addMenu.AddItem(new GUIContent(InspectorUtility.DisplayTypeName(typeList[i], friendlyNamespacePrefix)), false, addCallback, typeList[i]);
            }

            addMenu.ShowAsContext();
        }
예제 #28
0
        private GenericMenu GenerateMenu(List <AnimationWindowHierarchyNode> interactedNodes, bool enabled)
        {
            List <AnimationWindowCurve> curves = GetCurvesAffectedByNodes(interactedNodes, false);
            // Linked curves are like regular affected curves but always include transform siblings
            List <AnimationWindowCurve> linkedCurves = GetCurvesAffectedByNodes(interactedNodes, true);

            bool forceGroupRemove = curves.Count == 1 ? AnimationWindowUtility.ForceGrouping(curves[0].binding) : false;

            GenericMenu menu = new GenericMenu();

            // Remove curves
            GUIContent removePropertyContent = new GUIContent(curves.Count > 1 || forceGroupRemove ? "Remove Properties" : "Remove Property");

            if (!enabled)
            {
                menu.AddDisabledItem(removePropertyContent);
            }
            else
            {
                menu.AddItem(removePropertyContent, false, RemoveCurvesFromSelectedNodes);
            }

            // Change rotation interpolation
            bool showInterpolation = true;

            EditorCurveBinding[] curveBindings = new EditorCurveBinding[linkedCurves.Count];
            for (int i = 0; i < linkedCurves.Count; i++)
            {
                curveBindings[i] = linkedCurves[i].binding;
            }
            RotationCurveInterpolation.Mode rotationInterpolation = GetRotationInterpolationMode(curveBindings);
            if (rotationInterpolation == RotationCurveInterpolation.Mode.Undefined)
            {
                showInterpolation = false;
            }
            else
            {
                foreach (var node in interactedNodes)
                {
                    if (!(node is AnimationWindowHierarchyPropertyGroupNode))
                    {
                        showInterpolation = false;
                    }
                }
            }
            if (showInterpolation)
            {
                string legacyWarning = state.activeAnimationClip.legacy ? " (Not fully supported in Legacy)" : "";
                GenericMenu.MenuFunction2 nullMenuFunction2 = null;
                menu.AddItem(EditorGUIUtility.TrTextContent("Interpolation/Euler Angles" + legacyWarning), rotationInterpolation == RotationCurveInterpolation.Mode.RawEuler, enabled ? ChangeRotationInterpolation : nullMenuFunction2, RotationCurveInterpolation.Mode.RawEuler);
                menu.AddItem(EditorGUIUtility.TrTextContent("Interpolation/Euler Angles (Quaternion)"), rotationInterpolation == RotationCurveInterpolation.Mode.Baked, enabled ? ChangeRotationInterpolation : nullMenuFunction2, RotationCurveInterpolation.Mode.Baked);
                menu.AddItem(EditorGUIUtility.TrTextContent("Interpolation/Quaternion"), rotationInterpolation == RotationCurveInterpolation.Mode.NonBaked, enabled ? ChangeRotationInterpolation : nullMenuFunction2, RotationCurveInterpolation.Mode.NonBaked);
            }

            // Menu items that are only applicaple when in animation mode:
            if (state.previewing)
            {
                menu.AddSeparator("");

                bool allHaveKeys  = true;
                bool noneHaveKeys = true;
                foreach (AnimationWindowCurve curve in curves)
                {
                    bool curveHasKey = curve.HasKeyframe(state.time);
                    if (!curveHasKey)
                    {
                        allHaveKeys = false;
                    }
                    else
                    {
                        noneHaveKeys = false;
                    }
                }

                string str;

                str = "Add Key";
                if (allHaveKeys || !enabled)
                {
                    menu.AddDisabledItem(new GUIContent(str));
                }
                else
                {
                    menu.AddItem(new GUIContent(str), false, AddKeysAtCurrentTime, curves);
                }

                str = "Delete Key";
                if (noneHaveKeys || !enabled)
                {
                    menu.AddDisabledItem(new GUIContent(str));
                }
                else
                {
                    menu.AddItem(new GUIContent(str), false, DeleteKeysAtCurrentTime, curves);
                }
            }

            return(menu);
        }
예제 #29
0
    public static UnityEditorInternal.ReorderableList Create(List <ScreenshotData> configsList, GenericMenu.MenuFunction2 menuItemHandler)
    {
        var reorderableList = new UnityEditorInternal.ReorderableList(configsList, typeof(ScreenshotData), true, false, true, true);

        reorderableList.elementHeight       = EditorGUIUtility.singleLineHeight + 4;
        reorderableList.drawElementCallback = (position, index, isActive, isFocused) => {
            const float enabledWidth = 15f;
            const float cameraWidth  = 100f;
            const float textWidth    = 10f;
            const float sizeWidth    = 50f;
            const float multWidth    = 30f;
            const float uiWidth      = 15f;
            const float space        = 10f;
            const float minNameWidth = 100f;

            const float singleWidth = 10;

            var config    = configsList[index];
            var nameWidth = position.width - space * 6 - enabledWidth - cameraWidth - textWidth - sizeWidth * 2 - multWidth - uiWidth - singleWidth * 21;
            if (nameWidth < minNameWidth)
            {
                nameWidth = minNameWidth;
            }

            position.y      += 2;
            position.height -= 4;

            position.x      += space;
            position.width   = enabledWidth;
            config.isEnabled = EditorGUI.Toggle(position, config.isEnabled);

            EditorGUI.BeginDisabledGroup(!config.isEnabled);
            position.x         += position.width + space;
            position.width      = cameraWidth;
            config.targetCamera = (ScreenshooterTargetCamera)EditorGUI.EnumPopup(position, config.targetCamera);

            position.x    += position.width + space;
            position.width = nameWidth;
            config.name    = EditorGUI.TextField(position, config.name);

            position.x    += position.width + space;
            position.width = singleWidth * 4;
            EditorGUI.LabelField(position, "Size");

            position.x         += position.width;
            position.width      = sizeWidth;
            config.resolution.x = EditorGUI.IntField(position, (int)config.resolution.x);

            position.x    += position.width;
            position.width = textWidth;
            EditorGUI.LabelField(position, "x");

            position.x         += position.width;
            position.width      = sizeWidth;
            config.resolution.y = EditorGUI.IntField(position, (int)config.resolution.y);

            position.x    += position.width + space;
            position.width = singleWidth * 9;
            EditorGUI.LabelField(position, "Size Multiplier");

            position.x    += position.width;
            position.width = multWidth;
            config.resolutionMultiplier = EditorGUI.FloatField(position, config.resolutionMultiplier);

            position.x    += position.width + space;
            position.width = singleWidth * 2;
            EditorGUI.LabelField(position, "UI");

            position.x    += position.width;
            position.width = uiWidth;
            if (config.targetCamera == ScreenshooterTargetCamera.GameView)
            {
                config.captureOverlayUI = EditorGUI.Toggle(position, config.captureOverlayUI);
            }
            else
            {
                EditorGUI.BeginDisabledGroup(true);
                config.captureOverlayUI = EditorGUI.Toggle(position, false);
                EditorGUI.EndDisabledGroup();
            }
            EditorGUI.EndDisabledGroup();
        };

        reorderableList.onAddDropdownCallback = (buttonRect, list) => {
            var menu = new GenericMenu();

            menu.AddItem(new GUIContent("Custom"), false, menuItemHandler, new ScreenshotData("Custom", 1920, 1080));
            menu.AddSeparator("");

            foreach (var config in PredefinedConfigs.Android)
            {
                if (config is SeparatorScreenshotData)
                {
                    menu.AddSeparator("Android/");
                }
                else
                {
                    var label = "Android/" + config.name + " (" + config.resolution.x + "x" + config.resolution.y + ") (Portrait)";
                    menu.AddItem(new GUIContent(label), false, menuItemHandler, config);
                }
            }
            menu.AddSeparator("Android/");
            menu.AddSeparator("Android/");
            foreach (var config in PredefinedConfigs.Android)
            {
                if (config is SeparatorScreenshotData)
                {
                    menu.AddSeparator("Android/");
                }
                else
                {
                    ScreenshotData altData = config;
                    altData.resolution = new Vector2(config.resolution.y, config.resolution.x);
                    var label = "Android/" + altData.name + " (" + altData.resolution.x + "x" + altData.resolution.y + ") (Landscape)";
                    menu.AddItem(new GUIContent(label), false, menuItemHandler, altData);
                }
            }

            foreach (var config in PredefinedConfigs.iOS)
            {
                if (config is SeparatorScreenshotData)
                {
                    menu.AddSeparator("iOS/");
                }
                else
                {
                    var label = "iOS/" + config.name + " (" + config.resolution.x + "x" + config.resolution.y + ") (Portrait)";
                    menu.AddItem(new GUIContent(label), false, menuItemHandler, config);
                }
            }
            menu.AddSeparator("iOS/");
            menu.AddSeparator("iOS/");
            foreach (var config in PredefinedConfigs.iOS)
            {
                if (config is SeparatorScreenshotData)
                {
                    menu.AddSeparator("iOS/");
                }
                else
                {
                    ScreenshotData altData = config;
                    altData.resolution = new Vector2(config.resolution.y, config.resolution.x);
                    var label = "iOS/" + altData.name + " (" + altData.resolution.x + "x" + altData.resolution.y + ") (Landscape)";
                    menu.AddItem(new GUIContent(label), false, menuItemHandler, altData);
                }
            }

            foreach (var config in PredefinedConfigs.Standalone)
            {
                if (config is SeparatorScreenshotData)
                {
                    menu.AddSeparator("Standalone/");
                }
                else
                {
                    var label = "Standalone/" + config.name + " (" + config.resolution.x + "x" + config.resolution.y + ")";
                    menu.AddItem(new GUIContent(label), false, menuItemHandler, config);
                }
            }

            menu.ShowAsContext();
        };

        return(reorderableList);
    }
        private void CreatePopupMenuVersionControl(string title, EditorSettingsInspector.PopupElement[] elements, string selectedValue, GenericMenu.MenuFunction2 func)
        {
            int        num     = Array.FindIndex <EditorSettingsInspector.PopupElement>(elements, (EditorSettingsInspector.PopupElement typeElem) => typeElem.id == selectedValue);
            GUIContent content = new GUIContent(elements[num].content);

            this.CreatePopupMenu(title, content, elements, num, func);
        }
 private void CreatePopupMenu(string title, EditorSettingsInspector.PopupElement[] elements, int selectedIndex, GenericMenu.MenuFunction2 func)
 {
     this.CreatePopupMenu(title, elements[selectedIndex].content, elements, selectedIndex, func);
 }
예제 #32
0
 public static void AddItem(this GenericMenu current, string label, bool state, GenericMenu.MenuFunction2 method, object data)
 {
     current.AddItem(new GUIContent(label), state, method, data);
 }