Example #1
0
        public void DrawFields(Type componentType, object component, ECSContext ecsContext, string searchTerm, FieldInfo[] fields)
        {
            foreach (FieldInfo field in fields)
            {
                string fieldName = field.Name;

                if (!SearchMatches(searchTerm, fieldName))
                {
                    // Does not match search term, skip it
                    continue;
                }

                Type fieldType = field.FieldType;

                VariableAttributes variableAttributes = VariableAttributes.None;

                // See https://stackoverflow.com/a/10261848
                if (field.IsLiteral && !field.IsInitOnly)
                {
                    variableAttributes = VariableAttributes.Constant;

                    // Prevent SetValue as it will result in a FieldAccessException
                    variableAttributes |= VariableAttributes.ReadOnly;
                }
                if (field.IsStatic)
                {
                    variableAttributes |= VariableAttributes.Static;
                }

                string tooltip = TypeUtility.GetTooltip(field, variableAttributes);

                if ((variableAttributes & VariableAttributes.ReadOnly) != 0)
                {
                    GUI.enabled = false;
                }

                DrawVariable(fieldType, fieldName, component != null ? field.GetValue(component) : null, tooltip, variableAttributes, field.GetCustomAttributes(), true, componentType, newValue =>
                {
                    if ((variableAttributes & VariableAttributes.ReadOnly) == 0)
                    {
                        field.SetValue(component, newValue);

#if ECS_EXISTS
                        if (ecsContext != null)
                        {
                            ECSAccess.SetComponentData(ecsContext.EntityManager, ecsContext.Entity, ecsContext.ComponentType, component);
                        }
#endif
                    }
                });

                if ((variableAttributes & VariableAttributes.ReadOnly) != 0)
                {
                    GUI.enabled = true;
                }
            }
        }
Example #2
0
        public static GenericMenu GetMenu(object o, ECSContext inspectedECSContext)
        {
            var menu = new GenericMenu();

            if (TypeUtility.IsNull(o))
            {
                return(menu);
            }

            if (o is MonoScript monoScript)
            {
                Type classType = monoScript.GetClass();
                if (classType != null)
                {
                    if (classType.IsSubclassOf(typeof(ScriptableObject)))
                    {
                        menu.AddItem(new GUIContent("Instantiate Asset"), false, InstantiateScript, classType);
                    }
                    else if (classType.IsSubclassOf(typeof(Component)))
                    {
                        menu.AddItem(new GUIContent("Instantiate In Scene"), false, InstantiateScript, classType);
                    }
                }
            }

            if (o is GameObject gameObject)
            {
                menu.AddItem(new GUIContent("Set Name From First Script"), false, SetNameFromFirstScript, gameObject);
            }

            if (o is Object unityObject)
            {
                menu.AddItem(new GUIContent("Set Name From Type"), false, () => unityObject.name = o.GetType().Name);
            }

            if (o is Texture2D)
            {
                menu.AddItem(new GUIContent("Export Texture"), false, ExportTexture, o);
            }

            if (o is Component component)
            {
                menu.AddItem(new GUIContent("Remove Component"), false, () =>
                {
                    Undo.DestroyObjectImmediate(component);
                });
            }

#if ECS_EXISTS
            if (inspectedECSContext != null && o.GetType().GetInterfaces().Contains(typeof(IComponentData)))
            {
                menu.AddItem(new GUIContent("Remove Component"), false, () =>
                {
                    inspectedECSContext.EntityManager.RemoveComponent(inspectedECSContext.Entity, new ComponentType(o.GetType()));
                });
            }

            if (o is Translation translation)
            {
                menu.AddItem(new GUIContent("Focus In Scene View"), false, () =>
                {
                    SceneView sceneView = SceneView.lastActiveSceneView;
                    if (sceneView == null)
                    {
                        sceneView = EditorWindow.GetWindow <SceneView>();
                    }

                    sceneView.pivot = translation.Value;
                    sceneView.Show();
                });
            }
            if (o is LocalToWorld localToWorld)
            {
                menu.AddItem(new GUIContent("Focus In Scene View"), false, () =>
                {
                    SceneView sceneView = SceneView.lastActiveSceneView;
                    if (sceneView == null)
                    {
                        sceneView = EditorWindow.GetWindow <SceneView>();
                    }

                    sceneView.pivot = localToWorld.Position;
                    sceneView.Show();
                });
            }
#endif
            MonoScript targetMonoScript = GetMonoScriptForType(o.GetType());
            if (targetMonoScript != null)
            {
                menu.AddItem(new GUIContent("Select Script"), false, _ => Selection.activeObject = targetMonoScript, targetMonoScript);
                menu.AddItem(new GUIContent("Edit Script"), false, _ => AssetDatabase.OpenAsset(targetMonoScript), targetMonoScript);
            }

            menu.AddItem(new GUIContent("Copy As JSON (Unity JsonUtility)"), false, CopyAsJSON, o);

            return(menu);
        }
Example #3
0
        void OnGUI()
        {
            // Flexible width for the label based on overall width
            EditorGUIUtility.labelWidth = Mathf.Round(EditorGUIUtility.currentViewWidth * 0.4f);
            // Use inline controls if there is enough horizontal room
            EditorGUIUtility.wideMode = EditorGUIUtility.currentViewWidth > 400;

            // Frame rate tracking
            if (Event.current.type == EventType.Repaint)
            {
                AnimationHelper.UpdateTime();
            }

            current = this;

            CleanStacks();

            DrawToolbar();

            Type[]       inspectedTypes       = null;
            object[]     inspectedContexts    = null;
            ECSContext[] inspectedECSContexts = null;

            GUILayout.Space(9);

            string buttonPrefix = "";

#if ECS_EXISTS
            int selectionWrapWidth = 465;
#else
            int selectionWrapWidth = 400;
#endif
            if (EditorGUIUtility.currentViewWidth > selectionWrapWidth)
            {
                EditorGUILayout.BeginHorizontal();
                GUILayout.Label("Selection Helpers");
            }
            else
            {
                buttonPrefix = "Select ";
            }

            var popupRect = GUILayoutUtility.GetLastRect();
            popupRect.width = EditorGUIUtility.currentViewWidth;

            if (GUILayout.Button(new GUIContent(buttonPrefix + "Type From Assembly"), EditorStyles.miniButton))
            {
                TypeSelectDropdown dropdown = new TypeSelectDropdown(new AdvancedDropdownState(), SetSelection);
                dropdown.Show(popupRect);
            }

            if (GUILayout.Button(new GUIContent(buttonPrefix + "Loaded Unity Object"), EditorStyles.miniButton))
            {
                UnityObjectSelectDropdown dropdown = new UnityObjectSelectDropdown(new AdvancedDropdownState(), SetSelection);
                dropdown.Show(popupRect);
            }

#if ECS_EXISTS
            if (GUILayout.Button(new GUIContent(buttonPrefix + "ECS System"), EditorStyles.miniButton))
            {
                ECSSystemSelectDropdown dropdown = new ECSSystemSelectDropdown(new AdvancedDropdownState(), SetSelection);
                dropdown.Show(popupRect);
            }
#endif

            if (EditorGUIUtility.currentViewWidth > selectionWrapWidth)
            {
                EditorGUILayout.EndHorizontal();
            }

            if (activeSelection.IsEmpty)
            {
                GUILayout.FlexibleSpace();
                GUIStyle style = new GUIStyle(EditorStyles.wordWrappedLabel)
                {
                    alignment = TextAnchor.MiddleCenter
                };
                GUILayout.Label("No object selected.\n\nSelect something in Unity or use one of the selection helper buttons.", style);
                GUILayout.FlexibleSpace();
                return;
            }

            if (activeSelection.Object != null)
            {
                if (activeSelection.Object is GameObject selectedGameObject)
                {
                    List <object> components = selectedGameObject.GetComponents <Component>().Cast <object>().ToList();
                    components.RemoveAll(item => item == null);
                    components.Insert(0, selectedGameObject);
                    inspectedContexts = components.ToArray();
                }
#if ECS_EXISTS
                else if (activeSelection.Object is EntitySelectionProxy entitySelectionProxy)
                {
                    EntityManager currentEntityManager = entitySelectionProxy.World.EntityManager;
                    string        name = currentEntityManager.GetName(entitySelectionProxy.Entity);

                    if (string.IsNullOrEmpty(name))
                    {
                        name = "Entity " + entitySelectionProxy.Entity.Index;
                    }

                    inspectedContexts       = new object [1 + currentEntityManager.GetComponentCount(entitySelectionProxy.Entity)];
                    inspectedContexts[0]    = activeSelection.Object;
                    inspectedECSContexts    = new ECSContext[1 + currentEntityManager.GetComponentCount(entitySelectionProxy.Entity)];
                    inspectedECSContexts[0] = new ECSContext {
                        EntityManager = currentEntityManager, Entity = entitySelectionProxy.Entity
                    };

                    NativeArray <ComponentType> types = currentEntityManager.GetComponentTypes(entitySelectionProxy.Entity);
                    for (var index = 0; index < types.Length; index++)
                    {
                        object componentData = ECSAccess.GetComponentData(currentEntityManager, entitySelectionProxy.Entity, types[index]);

                        inspectedContexts[1 + index]    = componentData;
                        inspectedECSContexts[1 + index] = new ECSContext {
                            EntityManager = currentEntityManager, Entity = entitySelectionProxy.Entity, ComponentType = types[index]
                        };
                    }

                    types.Dispose();
                }
#endif
                else
                {
                    inspectedContexts = new[] { activeSelection.Object };
                }

                inspectedTypes = inspectedContexts.Select(x => x.GetType()).ToArray();
            }
            else
            {
                inspectedTypes = new[] { activeSelection.Type };

                inspectedContexts = new Type[] { null };
            }

            if (inspectedECSContexts == null)
            {
                inspectedECSContexts = new ECSContext[inspectedContexts.Length];
            }

            GUILayout.Space(5);
            searchTerm = searchField.OnToolbarGUI(searchTerm);

            SidekickEditorGUI.BeginLabelHighlight(searchTerm);

            mode = SidekickUtility.EnumToolbar(mode);

            GUILayout.Space(5);
            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);

            for (int i = 0; i < inspectedTypes.Length; i++)
            {
                Type type = inspectedTypes[i];

                var inspectedContext    = inspectedContexts[i];
                var inspectedECSContext = inspectedECSContexts[i];

                bool?activeOrEnabled = inspectedContext switch
                {
                    GameObject gameObject => gameObject.activeSelf,
                    Behaviour behaviour => behaviour.enabled,
                    _ => null
                };

                if (typesHidden.All(row => row.Key != type))
                {
                    typesHidden.Add(new KeyValuePair <Type, bool>(type, false));
                }

                int index = typesHidden.FindIndex(row => row.Key == type);

                string name;
                if (inspectedContexts[0] != null)
                {
                    if (activeOrEnabled.HasValue)
                    {
                        name = "              " + type.Name;
                    }
                    else
                    {
                        name = "       " + type.Name;
                    }

                    if (i == 0 && inspectedContexts[i] is Object unityObject)
                    {
                        name += $" ({unityObject.name})";
                    }
                }
                else
                {
                    name = type.Name + " (Class)";
                }

                GUIContent content = new GUIContent(name, $"{type.FullName}, {type.Assembly.FullName}");

                Rect foldoutRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.foldoutHeader);

                Rect toggleRect = foldoutRect;
                toggleRect.xMin += 36;
                toggleRect.width = 20;

                Rect iconRect = foldoutRect;
                iconRect.xMin  += 16;
                iconRect.yMin  += 1;
                iconRect.height = iconRect.width = 16;

                // Have to do this before BeginFoldoutHeaderGroup otherwise it'll consume the mouse down event
                if (activeOrEnabled.HasValue && SidekickEditorGUI.DetectClickInRect(toggleRect))
                {
                    switch (inspectedContexts[i])
                    {
                    case GameObject gameObject:
                        gameObject.SetActive(!gameObject.activeSelf);
                        break;

                    case Behaviour behaviour:
                        behaviour.enabled = !behaviour.enabled;
                        break;
                    }
                }

                bool foldout = EditorGUI.BeginFoldoutHeaderGroup(foldoutRect, !typesHidden[index].Value, content, EditorStyles.foldoutHeader, rect => ClassUtilities.GetMenu(inspectedContext, inspectedECSContext).DropDown(rect));

                Texture icon = SidekickEditorGUI.GetIcon(inspectedContexts[i], type);
                if (icon != null)
                {
                    GUI.DrawTexture(iconRect, icon);
                }

                // Right click context menu
                if (SidekickEditorGUI.DetectClickInRect(foldoutRect, 1))
                {
                    ClassUtilities.GetMenu(inspectedContext, inspectedECSContext).DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                }

                if (activeOrEnabled.HasValue)
                {
                    EditorGUI.Toggle(toggleRect, activeOrEnabled.Value);
                }

                EditorGUILayout.EndFoldoutHeaderGroup();

                typesHidden[index] = new KeyValuePair <Type, bool>(type, !foldout);

                if (!typesHidden[index].Value)
                {
                    SidekickEditorGUI.DrawSplitter(0.5f);

                    EditorGUI.indentLevel++;

                    BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly;

                    if (inspectedContext != null) // Is this an object instance?
                    {
                        bindingFlags |= BindingFlags.Instance;
                    }

                    var typeScope = type;

                    while (typeScope != null)
                    {
                        if (InspectionExclusions.GetExcludedTypes().Contains(typeScope))
                        {
                            break;
                        }

                        if (typeScope != type)
                        {
                            SidekickEditorGUI.DrawTypeChainHeader(new GUIContent(": " + typeScope.Name));
                        }

                        FieldInfo[]    fields     = typeScope.GetFields(bindingFlags);
                        PropertyInfo[] properties = typeScope.GetProperties(bindingFlags);
                        MethodInfo[]   methods    = typeScope.GetMethods(bindingFlags);

                        // Hide methods and backing fields that have been generated for properties
                        if (SidekickSettings.HideAutoGenerated)
                        {
                            List <MethodInfo> methodList = new List <MethodInfo>(methods.Length);

                            foreach (MethodInfo method in methods)
                            {
                                if (!TypeUtility.IsPropertyMethod(method, typeScope))
                                {
                                    methodList.Add(method);
                                }
                            }

                            methods = methodList.ToArray();

                            List <FieldInfo> fieldList = new List <FieldInfo>(fields.Length);

                            for (int j = 0; j < fields.Length; j++)
                            {
                                if (!TypeUtility.IsBackingField(fields[j], typeScope))
                                {
                                    fieldList.Add(fields[j]);
                                }
                            }

                            fields = fieldList.ToArray();
                        }


                        FieldInfo[] events = typeScope.GetFields(bindingFlags);

                        if (mode == InspectorMode.Fields)
                        {
                            fieldPane.DrawFields(inspectedTypes[i], inspectedContexts[i], inspectedECSContext, searchTerm, fields);
                        }
                        else if (mode == InspectorMode.Properties)
                        {
                            propertyPane.DrawProperties(inspectedTypes[i], inspectedContexts[i], searchTerm, properties);
                        }
                        else if (mode == InspectorMode.Methods)
                        {
                            methodPane.DrawMethods(inspectedTypes[i], inspectedContexts[i], searchTerm, methods);
                        }
                        else if (mode == InspectorMode.Events)
                        {
                            eventPane.DrawEvents(inspectedTypes[i], inspectedContexts[i], searchTerm, events);
                        }

                        typeScope = typeScope.BaseType;
                    }


                    EditorGUI.indentLevel--;
                }

                SidekickEditorGUI.DrawSplitter();
            }

            EditorGUILayout.Space();
            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();

            if (inspectedTypes[0] == typeof(GameObject)
#if ECS_EXISTS
                || inspectedTypes[0] == typeof(EntitySelectionProxy)
#endif
                )
            {
                bool pressed    = GUILayout.Button("Add Component", GUILayout.Width(230), GUILayout.Height(24));
                var  popupRect2 = GUILayoutUtility.GetLastRect();
                popupRect2.width = EditorGUIUtility.currentViewWidth;
                if (pressed)
                {
                    if (inspectedTypes[0] == typeof(GameObject))
                    {
                        TypeSelectDropdown dropdown = new TypeSelectDropdown(new AdvancedDropdownState(), type =>
                        {
                            ((GameObject)inspectedContexts[0]).AddComponent(type);
                        }, new[] { typeof(Component) });
                        dropdown.Show(popupRect2);
                    }
#if ECS_EXISTS
                    else if (inspectedTypes[0] == typeof(EntitySelectionProxy))
                    {
                        TypeSelectDropdown dropdown = new TypeSelectDropdown(new AdvancedDropdownState(), type =>
                        {
                            inspectedECSContexts[0].EntityManager.AddComponent(inspectedECSContexts[0].Entity, ComponentType.ReadWrite(type));
                        }, null, new [] { typeof(IComponentData) });
                        dropdown.Show(popupRect2);
                    }
#endif
                }
            }

            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.EndScrollView();

            if (mode == InspectorMode.Methods)
            {
                methodPane.PostDraw();
            }


            //if(AnimationHelper.AnimationActive)
            {
                // Cause repaint on next frame
                Repaint();
                if (Event.current.type == EventType.Repaint)
                {
                    //AnimationHelper.ClearAnimationActive();
                }
            }

            SidekickEditorGUI.EndLabelHighlight();
        }