Exemplo n.º 1
0
    void OnGUI()
    {
        if (AlignEditor.editorPath == null)
        {
            AlignEditor.editorPath = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this)));
        }

        title      = "AE Grid v" + AlignEditor.VERSION;
        mainScroll = EditorGUILayout.BeginScrollView(mainScroll);
        // auto grid size is enabled for distribution (if there is more than 1 selected object)
        bool GUIWasEnabled = GUI.enabled;

        GUI.enabled = (Selection.transforms.Length > 1);

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel("Grid Size");
        Vector3 gridSize       = AlignEditor.gridSize;
        bool    wantedAutoSize = GUILayout.Toggle(AlignEditor.autoSize, "auto", "MiniButton", GUILayout.Width(70));

        if (wantedAutoSize != AlignEditor.autoSize)
        {
            Undo.RegisterUndo(this, "change auto grid size");
            AlignEditor.autoSize = wantedAutoSize;
        }
        EditorGUILayout.EndHorizontal();
        GUI.enabled = GUIWasEnabled;

        EditorGUILayout.BeginHorizontal();
        if (AlignEditor.autoSize && (Selection.transforms.Length > 1))
        {
            AlignEditor.calculatedGridSize = Mathf.Max(Mathf.CeilToInt(Mathf.Pow(Selection.transforms.Length, 1 / 3)), 2);
            EditorGUILayout.PrefixLabel("Every axis");
            GUILayout.Label("" + AlignEditor.calculatedGridSize);
        }
        else
        {
            Vector3 wantedGridSize = gridSize;
            GUILayout.Label("X");
            wantedGridSize.x = Mathf.Max(1, EditorGUILayout.IntField((int)gridSize.x));
            GUILayout.Label("Y");
            wantedGridSize.y = Mathf.Max(1, EditorGUILayout.IntField((int)gridSize.y));
            GUILayout.Label("Z");
            wantedGridSize.z = Mathf.Max(1, EditorGUILayout.IntField((int)gridSize.z));
            if (!wantedGridSize.Equals(gridSize))
            {
                Undo.RegisterUndo(this, "change grid size");
                AlignEditor.gridSize = wantedGridSize;
            }
        }
        EditorGUILayout.EndHorizontal();

        // Offset is enabled only for duplication (if there is only 1 selected object)
        GUIWasEnabled = GUI.enabled;
        GUI.enabled   = (Selection.transforms.Length == 1);
        Vector3 wantedOffset = EditorGUILayout.Vector3Field("Offset", AlignEditor.gridOffset);

        if (!wantedOffset.Equals(AlignEditor.gridOffset))
        {
            Undo.RegisterUndo(this, "change grid offset");
            AlignEditor.gridOffset = wantedOffset;
        }
        GUI.enabled = GUIWasEnabled;

        if (Selection.transforms.Length == 1)
        {
            EditorGUILayout.LabelField("Duplicate", Selection.activeTransform.name);
        }
        else if (Selection.transforms.Length > 1)
        {
            EditorGUILayout.LabelField("Distribute", "" + Selection.transforms.Length + " objects");
        }
        else
        {
            GUILayout.Label("Select 1 object to duplicate, N to distribute", EditorStyles.boldLabel);
        }
        EditorGUILayout.BeginHorizontal();
        GridButtonGUI(Selection.transforms);
        AlignEditor.SettingsButtonGUI();
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.EndScrollView();
    }
        protected override void DrawInspector()
        {
            serializedObject.Update();

            EditorGUI.BeginDisabledGroup(true);
            {
                EditorGUILayout.ObjectField(
                    "Script",
                    MonoScript.FromMonoBehaviour(session),
                    typeof(MonoScript),
                    false
                    );
            }
            EditorGUI.EndDisabledGroup();
            EditorGUILayout.Separator();

            tabSelection = GUILayout.Toolbar(tabSelection, tabTexts);

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.Label(":: ", EditorStyles.boldLabel);
            GUILayout.Label(tabTexts[tabSelection], EditorStyles.boldLabel);
            GUILayout.Label(" ::", EditorStyles.boldLabel);
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            Rect  rectBox = EditorGUILayout.BeginVertical("Box");
            float lw      = EditorGUIUtility.labelWidth;

            switch (tabSelection)
            {
            case 0:
                EditorGUIUtility.labelWidth = rectBox.width - 36f;
                EditorGUI.indentLevel++;
                DrawPropertiesFromUpTo("endOnQuit", "setAsMainInstance");
                EditorGUI.BeginDisabledGroup(true);
                EditorGUILayout.Toggle(new GUIContent("Ad Hoc Header Add", "Now permanently enabled. Results that are not listed in Custom Headers can be added at any time."), true);
                EditorGUI.EndDisabledGroup();
                DrawPropertiesFromUpTo("setAsMainInstance", "storeSessionSettings");
                EditorGUIUtility.labelWidth = lw;
                EditorGUILayout.BeginHorizontal();
                GUILayout.Space(16);
                GUILayout.Label("User Interface & Startup");
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Configure"))
                {
                    Object ui = session.GetComponentInChildren <UI.UIController>();
                    Selection.activeObject = ui;
                    InternalEditorUtility.SetIsInspectorExpanded(ui, true);
                }
                GUILayout.Space(14);
                EditorGUILayout.EndHorizontal();
                EditorGUI.indentLevel--;
                GUILayout.Space(3);
                break;

            case 1:
                EditorGUIUtility.labelWidth = rectBox.width - 36f;
                EditorGUI.indentLevel++;
                EditorGUI.BeginDisabledGroup(session.hasInitialised);
                DrawPropertiesFromUpTo("storeSessionSettings", "customHeaders");
                EditorGUIUtility.labelWidth = lw;
                DrawPropertiesFromUpTo("customHeaders", "onSessionBegin");
                EditorGUI.EndDisabledGroup();
                EditorGUI.indentLevel--;
                break;

            case 2:
                EditorGUILayout.HelpBox(
                    "The Data Handlers below define how your data will be stored."
                    + "You can select which Data Handlers will be used."
                    + "You may need to activate/deactivate different handlers depending on your build target (Windows, Web, Quest).", MessageType.Info);
                EditorGUI.indentLevel++;
                DrawPropertiesFrom("dataHandlers");
                EditorGUI.indentLevel--;
                break;

            case 3:
                EditorGUILayout.HelpBox(
                    "These events are raised when the session/trial begins/ends. Use them to manipulate the scene to create your experiment manipulation. " +
                    "Importantly, the items within these events are called in order from top to bottom. You can reorder any added items by dragging the handle on the left.",
                    MessageType.Info);

                EditorGUILayout.Space();
                EditorGUILayout.HelpBox(GetTooltip(session.GetType().GetField("onSessionBegin")).tooltip, MessageType.Info);
                DrawPropertiesFromUpTo("onSessionBegin", "onTrialBegin");

                EditorGUILayout.Space();
                EditorGUILayout.HelpBox(GetTooltip(session.GetType().GetField("onTrialBegin")).tooltip, MessageType.Info);
                DrawPropertiesFromUpTo("onTrialBegin", "onTrialEnd");

                EditorGUILayout.Space();
                EditorGUILayout.HelpBox(GetTooltip(session.GetType().GetField("onTrialEnd")).tooltip, MessageType.Info);
                DrawPropertiesFromUpTo("onTrialEnd", "preSessionEnd");

                EditorGUILayout.Space();
                EditorGUILayout.HelpBox(GetTooltip(session.GetType().GetField("preSessionEnd")).tooltip, MessageType.Info);
                DrawPropertiesFromUpTo("preSessionEnd", "onSessionEnd");

                EditorGUILayout.Space();
                EditorGUILayout.HelpBox(GetTooltip(session.GetType().GetField("onSessionEnd")).tooltip, MessageType.Info);
                DrawPropertiesFromUpTo("onSessionEnd", "_hasInitialised");
                break;
            }
            EditorGUILayout.EndVertical();
            EditorGUILayout.Separator();
            DrawMonitorTab();
            //GUILayout.Button("Create a GitHub issue");
            //GUILayout.Button("Get help on the Wiki");

            serializedObject.ApplyModifiedProperties();
        }
        void DrawElementCallbackRect(Rect rect, int index, bool isActive, bool isFocused)
        {
            rect.height = 20f;
            // 防止出现空对象
            if (target.InvokeInfoList[index] == null)
            {
                target.InvokeInfoList[index] = new InvokeInfo();
            }

            // 获取方法所在脚本对象
            var        _element = target.InvokeInfoList[index];
            MonoScript _script  = null;

            if (_element.MethodInfo != null)
            {
                _script = (MonoScript)EditorGUI.ObjectField(rect, "Script",
                                                            UtilityAssets.AllScript.First(s => s.GetClass() == _element.MethodInfo.DeclaringType),
                                                            typeof(MonoScript), null);
            }
            else
            {
                _script = (MonoScript)EditorGUI.ObjectField(rect, "Script", null, typeof(MonoScript), null);
            }

            // 若找到了脚本对象
            if (_script != null)
            {
                // 查询脚本所含有的所有方法
                var _methods = target.FilterMethod(_script.GetClass().GetMethods(BindingFlags.Static | BindingFlags.Public));

                // 刷新调用信息
                if (_methods != null && _methods.Length > 0)
                {
                    bool _dirty       = false;
                    int  _methodIndex = -1;
                    // 查询调用信息在数组中的下标
                    if (_element.MethodInfo == null)
                    {
                        _dirty       = true;
                        _methodIndex = 0;
                    }
                    else
                    {
                        _methodIndex = Array.IndexOf(_methods, _element.MethodInfo);
                        if (_methodIndex < 0)
                        {
                            _dirty       = true;
                            _methodIndex = 0;
                        }
                    }

                    rect.y += 25;
                    var _buf = EditorGUI.Popup(rect, _methodIndex, Array.ConvertAll(_methods, m => m.Name));

                    if (_buf != _methodIndex)
                    {
                        _dirty       = true;
                        _methodIndex = _buf;
                    }

                    if (_dirty)
                    {
                        target.InitializeInvokeInfo(index, _methods[_methodIndex]);
                    }
                }
            }

            if (_element.MethodInfo != null)
            {
                var _parms = _element.parameterInfos;
                if (_parms != null)
                {
                    rect.y += 25f;
                    for (int i = 0; i < _parms.Length; i++)
                    {
                        _element.Propertys[i] = DrawParameter(rect, _parms[i], _element.Propertys[i]);
                        rect.y += 25f;
                    }
                }
            }
        }
Exemplo n.º 4
0
    void OnGUI()
    {
        if (AlignEditor.editorPath == null)
        {
            AlignEditor.editorPath = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this)));
        }

        title = "AllIn v" + AlignEditor.VERSION;
        ImagePosition wasPosition = AlignEditor.ButtonStyle;

        // v2.0 : automatic layout from ratio width/height
        if (this.position.width > this.position.height)
        {
            EditorGUILayout.BeginHorizontal();
            this.minSize = new Vector2(292, 58);
        }
        else
        {
            // Force image above for vertical layout
            if (wasPosition == ImagePosition.ImageLeft)
            {
                AlignEditor.ButtonStyle = ImagePosition.ImageAbove;
            }
            this.minSize = new Vector2(52, 256);
        }
        ClassicWindow.DetectAlignAxis();
        ClassicWindow.AlignButtonGUI(Selection.transforms, true);
        GridWindow.GridButtonGUI(Selection.transforms);
        CameraWindow.CameraButtonGUI(Selection.transforms);

        AlignEditor.SettingsButtonGUI();
        if (this.position.width > this.position.height)
        {
            EditorGUILayout.EndHorizontal();
        }
        else
        {
            AlignEditor.ButtonStyle = wasPosition;
        }
        // Restore the previous state of button style
    }
Exemplo n.º 5
0
 public static string GetAbsolutePath(MonoScript pScript)
 {
     return($"{Application.dataPath}/{AssetDatabase.GetAssetPath(pScript).Replace(".cs", "")}");
 }
Exemplo n.º 6
0
        void OnEnable()
        {
            if (target == null)
            {
                return;
            }

            var proCamera2DRooms = (ProCamera2DRooms)target;

            if (proCamera2DRooms.ProCamera2D == null)
            {
                return;
            }

            // Add Numeric Boundaries component if needed
            var numericBoundaries = proCamera2DRooms.ProCamera2D.GetComponent <ProCamera2DNumericBoundaries>();

            if (numericBoundaries == null)
            {
                proCamera2DRooms.ProCamera2D.gameObject.AddComponent <ProCamera2DNumericBoundaries>();
            }

            // Create Vector conversion methods
            switch (proCamera2DRooms.ProCamera2D.Axis)
            {
            case MovementAxis.XY:
                Vector3H  = vector => vector.x;
                Vector3V  = vector => vector.y;
                VectorHV  = (h, v) => new Vector3(h, v, 0);
                VectorHVD = (h, v, d) => new Vector3(h, v, d);
                break;

            case MovementAxis.XZ:
                Vector3H  = vector => vector.x;
                Vector3V  = vector => vector.z;
                VectorHV  = (h, v) => new Vector3(h, 0, v);
                VectorHVD = (h, v, d) => new Vector3(h, d, v);
                break;

            case MovementAxis.YZ:
                Vector3H  = vector => vector.z;
                Vector3V  = vector => vector.y;
                VectorHV  = (h, v) => new Vector3(0, v, h);
                VectorHVD = (h, v, d) => new Vector3(d, v, h);
                break;
            }

            // Script
            _script = MonoScript.FromMonoBehaviour(proCamera2DRooms);

            // Rooms List
            _roomsList = new ReorderableList(serializedObject, serializedObject.FindProperty("Rooms"), false, true, true, true);

            _roomsList.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, "Rooms");
            };

            _roomsList.onSelectCallback = (list) =>
            {
                _currentlyEditingRoom = _roomsList.index;
                SceneView.RepaintAll();
            };

            _roomsList.onAddCallback = (list) =>
            {
                var index = list.serializedProperty.arraySize;
                list.serializedProperty.arraySize++;
                list.index = index;

                var newEntry = list.serializedProperty.GetArrayElementAtIndex(list.count - 1);
                if (list.count > 1)
                {
                    var prevRect = list.serializedProperty.GetArrayElementAtIndex(list.count - 2).FindPropertyRelative("Dimensions").rectValue;
                    prevRect.x += prevRect.width;
                    newEntry.FindPropertyRelative("Dimensions").rectValue = prevRect;
                }
                else if (list.count == 1)
                {
                    newEntry.FindPropertyRelative("Dimensions").rectValue          = new Rect(0, 0, 10, 10);
                    newEntry.FindPropertyRelative("TransitionDuration").floatValue = 1f;
                    newEntry.FindPropertyRelative("ZoomScale").floatValue          = 1.5f;
                }

                _currentlyEditingRoom = index;
            };

            _roomsList.onRemoveCallback = (list) =>
            {
                _currentlyEditingRoom = -1;
                SceneView.RepaintAll();
                ReorderableList.defaultBehaviours.DoRemoveButton(list);
            };

            _roomsList.drawElementCallback = (rect, index, isActive, isFocused) =>
            {
                rect.y += 2;
                var element = _roomsList.serializedProperty.GetArrayElementAtIndex(index);

                EditorGUI.DropShadowLabel(new Rect(rect.x, rect.y + 3, 60, 10), "Room " + index);
                rect.y += 20;

#if UNITY_5
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 65, 10), new GUIContent("ID", "The room id"), EditorStyles.boldLabel);
#else
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 65, 10), new GUIContent("ID", "The room id"));
#endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 80,
                                            rect.y,
                                            100,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("ID"), GUIContent.none);

#if UNITY_5
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y, 65, 10), new GUIContent("Rect", "The room size and position"), EditorStyles.boldLabel);
#else
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y, 65, 10), new GUIContent("Rect", "The room size and position"));
#endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 260,
                                            rect.y,
                                            rect.width - 260,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("Dimensions"), GUIContent.none);

#if UNITY_5
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y + 45, 65, 10), new GUIContent("Ease Type", ""), EditorStyles.boldLabel);
#else
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y + 45, 65, 10), new GUIContent("Ease Type", ""));
#endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 80,
                                            rect.y + 45,
                                            100,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("TransitionEaseType"), GUIContent.none);

#if UNITY_5
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y + 45, 65, 10), new GUIContent("Duration", "How long it takes for the camera to reach this room"), EditorStyles.boldLabel);
#else
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y + 45, 65, 10), new GUIContent("Duration", "How long it takes for the camera to reach this room"));
#endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 260,
                                            rect.y + 45,
                                            rect.width - 260,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("TransitionDuration"), GUIContent.none);

#if UNITY_5
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y + 70, 65, 10), new GUIContent("Scale To Fit", "If checked, the camera will resize to fit the room"), EditorStyles.boldLabel);
#else
                EditorGUI.PrefixLabel(new Rect(rect.x, rect.y + 70, 65, 10), new GUIContent("Scale To Fit", "If checked, the camera will resize to fit the room"));
#endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 80,
                                            rect.y + 70,
                                            20,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("ScaleCameraToFit"), GUIContent.none);

                GUI.enabled = !element.FindPropertyRelative("ScaleCameraToFit").boolValue;
#if UNITY_5
                EditorGUI.PrefixLabel(new Rect(rect.x + 120, rect.y + 70, 65, 10), new GUIContent("Zoom", "If checked, the camera will zoom when entering the room"), EditorStyles.boldLabel);
#else
                EditorGUI.PrefixLabel(new Rect(rect.x + 120, rect.y + 70, 65, 10), new GUIContent("Zoom", "If checked, the camera will zoom when entering the room"));
#endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 160,
                                            rect.y + 70,
                                            20,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("Zoom"), GUIContent.none);
                GUI.enabled = true;

                GUI.enabled = !element.FindPropertyRelative("ScaleCameraToFit").boolValue&& element.FindPropertyRelative("Zoom").boolValue;
#if UNITY_5
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y + 70, 65, 10), new GUIContent("Scale", "The zoom scale"), EditorStyles.boldLabel);
#else
                EditorGUI.PrefixLabel(new Rect(rect.x + 200, rect.y + 70, 65, 10), new GUIContent("Scale", "The zoom scale"));
#endif
                EditorGUI.PropertyField(new Rect(
                                            rect.x + 260,
                                            rect.y + 70,
                                            rect.width - 260,
                                            EditorGUIUtility.singleLineHeight),
                                        element.FindPropertyRelative("ZoomScale"), GUIContent.none);
                GUI.enabled = true;
            };

            _roomsList.elementHeight = 130;
            _roomsList.draggable     = true;
        }
Exemplo n.º 7
0
 void OnEnable()
 {
     fP_Controller = (FP_Controller)target;
     cntrlr        = MonoScript.FromMonoBehaviour((FP_Controller)target);
 }
Exemplo n.º 8
0
        private void InstantiateSystem()
        {
            if (!handler || !logic || (!trigger && !triggerPrefab))
            {
                if (!EditorUtility.DisplayDialog("[PuzzleSystem] System Creation Warning",

                                                 "There is at least one empty field passed into the . The system will most likely work improperly unless you add missing components by yourself later. \n\nDo you want to continue the creation without the missing component(-s)?",

                                                 "Continue", "Cancel"))
                {
                    return;
                }
            }


            if (handler)
            {
                if (!handler.GetClass().IsSubclassOf(typeof(CorePuzzleHandler)) && handler.GetClass() != typeof(CorePuzzleHandler))
                {
                    EditorUtility.DisplayDialog("[PuzzleSystem] System Creation Failed",

                                                "The creation of the puzzle system has failed becuase inputted Handler component does not inherit its core elements.\n\nPlease, make sure that the script you are choosing is a subclass of CorePuzzleHandler.",

                                                "Ok");
                    handler = null;
                    return;
                }
            }

            if (logic)
            {
                if (!logic.GetClass().IsSubclassOf(typeof(CorePuzzleLogic)) && logic.GetClass() != typeof(CorePuzzleLogic))
                {
                    EditorUtility.DisplayDialog("[PuzzleSystem] Failed System Creation",

                                                "The creation of the puzzle system has failed becuase inputted Logic component does not inherit its core elements.\n\nPlease, make sure that the script you are choosing is a subclass of CorePuzzleLogic.",

                                                "Ok");
                    logic = null;
                    return;
                }
            }

            bool includeCollider = false;

            if (trigger && toolBarTriggerType == 1)
            {
                if (!trigger.GetClass().IsSubclassOf(typeof(CorePuzzleTrigger)) && trigger.GetClass() != typeof(CorePuzzleTrigger))
                {
                    EditorUtility.DisplayDialog("[PuzzleSystem] Failed System Creation",

                                                "The creation of the puzzle system has failed becuase inputted Trigger component does not inherit its core elements.\n\nPlease, make sure that the script you are choosing is a subclass of CorePuzzleTrigger.",

                                                "Ok");
                    trigger = null;
                    return;
                }

                includeCollider = trigger.GetClass().IsSubclassOf(typeof(CoreColliderBasedPuzzleTrigger));
            }


            // PuzzleSystem Creation -- parent object & triggers

            GameObject parentObj = new GameObject("PuzzleSystem");

            if (handler)
            {
                parentObj.AddComponent(handler.GetClass());
            }
            CorePuzzleLogic logicComponent = logic ? parentObj.AddComponent(logic.GetClass()) as CorePuzzleLogic : null;

            GameObject        temp = null;
            CorePuzzleTrigger tempTriggerComponent = null;

            CorePuzzleTrigger[] triggers = new CorePuzzleTrigger[triggerCount];

            for (int i = 0; i < triggerCount; i++)
            {
                if (toolBarTriggerType == 1)
                {
                    temp = new GameObject("Trigger");

                    if (includeCollider)
                    {
                        temp.AddComponent <BoxCollider>().isTrigger = true;
                    }

                    tempTriggerComponent = temp.AddComponent(trigger.GetClass()) as CorePuzzleTrigger;
                }
                else if (triggerPrefab)
                {
                    temp = Instantiate(triggerPrefab);
                    tempTriggerComponent = temp.GetComponent <CorePuzzleTrigger>();
                }

                if (temp)
                {
                    temp.transform.parent = parentObj.transform;
                }

                if (tempTriggerComponent)
                {
                    triggers[i] = tempTriggerComponent;
                }
            }


            if (toolBarTriggerType == 0 && triggers.Length > 0 && !triggers[0])
            {
                EditorUtility.DisplayDialog("[PuzzleSystem] Warning System Creation",

                                            "The prefab of the trigger, that was passed in for creating a system, does not contain any script that inherit CorePuzzleTrigger." +
                                            "\n\nThis means that the instantiated objects will not play the role of the triggers in the created puzzle system.",

                                            "Ok");
                return;
            }

            if (logicComponent)
            {
                logicComponent.SetTriggers(triggers);
            }
        }
        public override void OnInspectorGUI()
        {
            if (target == null)
            {
                return;
            }

            var proCamera2DRepeater = (ProCamera2DRepeater)target;

            serializedObject.Update();

            // Show script link
            GUI.enabled = false;
            _script     = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;
            GUI.enabled = true;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ProCamera2D"), _tooltip);

            if (proCamera2DRepeater.ProCamera2D == null)
            {
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);
            }

            // Object To Repeat
            EditorGUI.BeginChangeCheck();

            _tooltip = new GUIContent("Object To Repeat", "This is the object that you want to repeat. It may be a prefab or not.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ObjectToRepeat"), _tooltip);

            if (EditorGUI.EndChangeCheck())
            {
                var objectToRepeat = serializedObject.FindProperty("ObjectToRepeat").objectReferenceValue as Transform;
                if (objectToRepeat != null && objectToRepeat.GetComponent <SpriteRenderer>())
                {
                    var sprite = objectToRepeat.GetComponent <SpriteRenderer>();
                    var size   = new Vector2(sprite.bounds.max.x - sprite.bounds.min.x, sprite.bounds.max.y - sprite.bounds.min.y);

                    serializedObject.FindProperty("ObjectSize").vector2Value       = size;
                    serializedObject.FindProperty("ObjectBottomLeft").vector2Value = -size / 2f;
                }
            }

            if (proCamera2DRepeater.ObjectToRepeat == null)
            {
                EditorGUILayout.HelpBox("No object to repeat set. Please drag one to the field above.", MessageType.Error, true);
            }

            // Object Size
            _tooltip = new GUIContent("Object Size", "The size of the object to repeat (in world units).");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ObjectSize"), _tooltip);

            if (proCamera2DRepeater.ObjectSize.x <= 0)
            {
                proCamera2DRepeater.ObjectSize.x = .01f;
            }

            if (proCamera2DRepeater.ObjectSize.y <= 0)
            {
                proCamera2DRepeater.ObjectSize.y = .01f;
            }

            // Object Bottom Left
            _tooltip = new GUIContent("Object Bottom Left", "The bottom left position of your object in relation to it's pivot (in world units).");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ObjectBottomLeft"), _tooltip);

            // Object On Stage
            _tooltip = new GUIContent("Object On Stage", "Mark as selected if your original object to repeat is already placed on the scene.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ObjectOnStage"), _tooltip);

            // Repeat horizontal
            _tooltip = new GUIContent("Repeat Horizontal", "If enabled, the object will be repeated horizontally.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("_repeatHorizontal"), _tooltip);

            // Repeat vertical
            _tooltip = new GUIContent("Repeat Vertical", "If enabled, the object will be repeated vertically.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("_repeatVertical"), _tooltip);

            // Camera to use
            if (proCamera2DRepeater.CameraToUse == null)
            {
                proCamera2DRepeater.CameraToUse = proCamera2DRepeater.ProCamera2D.GameCamera;
            }

            var parallax = FindObjectOfType <ProCamera2DParallax>();

            if (parallax != null)
            {
                _tooltip = new GUIContent("Camera To Use", "Choose what camera is rendering the object to repeat.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("CameraToUse"), _tooltip);
            }

            if (serializedObject.ApplyModifiedProperties())
            {
                if (Application.isPlaying)
                {
                    proCamera2DRepeater.RepeatHorizontal = serializedObject.FindProperty("_repeatHorizontal").boolValue;
                    proCamera2DRepeater.RepeatVertical   = serializedObject.FindProperty("_repeatVertical").boolValue;
                }
            }
        }
Exemplo n.º 10
0
        public override void OnInspectorGUI()
        {
            if (target == null)
            {
                return;
            }

            var proCamera2DPanAndZoom = (ProCamera2DPanAndZoom)target;

            serializedObject.Update();

            // Show script link
            GUI.enabled = false;
            _script     = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;
            GUI.enabled = true;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ProCamera2D"), _tooltip);

            if (proCamera2DPanAndZoom.ProCamera2D == null)
            {
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);
            }

            EditorGUILayout.Space();

            // Disable over uGUI
            _tooltip = new GUIContent("Disable Over uGUI", "If enabled, the camera won't pan or zoom if the user has a pointer (or touch) over a UI element");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("DisableOverUGUI"), _tooltip);

            // Allow Zoom
            _tooltip = new GUIContent("Allow Zoom", "If enabled, the user will be able to manually zoom the camera");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("AllowZoom"), _tooltip);

            if (proCamera2DPanAndZoom.AllowZoom)
            {
                EditorGUI.indentLevel = 1;

                // Mouse zoom speed
                _tooltip = new GUIContent("Mouse Zoom Speed", "The speed at which to zoom when using the mouse wheel (Desktop Only)");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("MouseZoomSpeed"), _tooltip);

                // Pinch zoom speed
                _tooltip = new GUIContent("Pinch Zoom Speed", "The speed at which to zoom when using the pinch gesture (Mobile Only)");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("PinchZoomSpeed"), _tooltip);

                // Zoom smoothness
                _tooltip = new GUIContent("Zoom Smoothness", "The smoothness of the zoom");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("ZoomSmoothness"), _tooltip);

                // Max zoom in amount
                _tooltip = new GUIContent("Max Zoom In Amount", "Represents the maximum amount the camera should zoom in");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("MaxZoomInAmount"), _tooltip);

                // Max zoom in amount
                _tooltip = new GUIContent("Max Zoom Out Amount", "Represents the maximum amount the camera should zoom out");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("MaxZoomOutAmount"), _tooltip);

                // Zoom to input center
                _tooltip = new GUIContent("Zoom To Input Center", "If enabled, the camera will zoom to the current input position (mouse or touch). If disabled, the camera will zoom to its center");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("ZoomToInputCenter"), _tooltip);

                EditorGUI.indentLevel = 0;

                EditorGUILayout.Space();
            }

            // Allow Pan
            _tooltip = new GUIContent("Allow Pan", "If enabled, the user will be able to manually pan the camera");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("AllowPan"), _tooltip);

            if (proCamera2DPanAndZoom.AllowPan)
            {
                EditorGUI.indentLevel = 1;

                // Use pan by drag
                _tooltip = new GUIContent("Use Drag Pan", "Pan the camera by dragging the 'world'");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("UsePanByDrag"), _tooltip);

                if (proCamera2DPanAndZoom.UsePanByDrag)
                {
                    EditorGUI.indentLevel = 2;
                    _tooltip = new GUIContent("Drag Speed Multiplier", "The speed at which to pan the camera");
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("DragPanSpeedMultiplier"), _tooltip);

                    _tooltip = new GUIContent("Draggable Area", "A normalized screen space area where the drag is active. Leave to default to use the whole screen");
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("DraggableAreaRect"), _tooltip);

                    _tooltip = new GUIContent("Stop Speed On Drag Start", "How fast the camera inertia stops once the user starts dragging");
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("StopSpeedOnDragStart"), _tooltip);
                    EditorGUI.indentLevel = 1;
                }

                // Use pan by move to edges
                _tooltip = new GUIContent("Use Edges Pan", "Pan the camera by moving the mouse to the edges of the screen (Desktop only)");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("UsePanByMoveToEdges"), _tooltip);

                if (proCamera2DPanAndZoom.UsePanByMoveToEdges)
                {
                    EditorGUI.indentLevel = 2;
                    _tooltip = new GUIContent("Edges Pan Speed", "The speed at which the camera will move when the mouse reaches the edges of the screen");
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("EdgesPanSpeed"), _tooltip);

                    _tooltip = new GUIContent("Top Pan Edge", "If the mouse pointer goes beyond this edge the camera will start moving vertically");
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("TopPanEdge"), _tooltip);

                    _tooltip = new GUIContent("Bottom Pan Edge", "If the mouse pointer goes beyond this edge the camera will start moving vertically");
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("BottomPanEdge"), _tooltip);

                    _tooltip = new GUIContent("Left Pan Edge", "If the mouse pointer goes beyond this edge the camera will start moving horizontally");
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("LeftPanEdge"), _tooltip);

                    _tooltip = new GUIContent("Right Pan Edge", "If the mouse pointer goes beyond this edge the camera will start moving horizontally");
                    EditorGUILayout.PropertyField(serializedObject.FindProperty("RightPanEdge"), _tooltip);
                }

                EditorGUI.indentLevel = 0;
            }

            // Apply properties
            serializedObject.ApplyModifiedProperties();

            // Limit
            if (proCamera2DPanAndZoom.MaxZoomInAmount < 1f)
            {
                proCamera2DPanAndZoom.MaxZoomInAmount = 1f;
            }

            if (proCamera2DPanAndZoom.MaxZoomOutAmount < 1f)
            {
                proCamera2DPanAndZoom.MaxZoomOutAmount = 1f;
            }

            if (proCamera2DPanAndZoom.ZoomSmoothness < 0f)
            {
                proCamera2DPanAndZoom.ZoomSmoothness = 0f;
            }

            if (proCamera2DPanAndZoom.DraggableAreaRect.width < 0f)
            {
                proCamera2DPanAndZoom.DraggableAreaRect.width = 0f;
            }

            if (proCamera2DPanAndZoom.DraggableAreaRect.width > 1f)
            {
                proCamera2DPanAndZoom.DraggableAreaRect.width = 1f;
            }

            if (proCamera2DPanAndZoom.DraggableAreaRect.height < 0f)
            {
                proCamera2DPanAndZoom.DraggableAreaRect.height = 0f;
            }

            if (proCamera2DPanAndZoom.DraggableAreaRect.height > 1f)
            {
                proCamera2DPanAndZoom.DraggableAreaRect.height = 1f;
            }

            if (proCamera2DPanAndZoom.DraggableAreaRect.x < -.5f)
            {
                proCamera2DPanAndZoom.DraggableAreaRect.x = -.5f;
            }

            if (proCamera2DPanAndZoom.DraggableAreaRect.x > .5f)
            {
                proCamera2DPanAndZoom.DraggableAreaRect.x = .5f;
            }

            if (proCamera2DPanAndZoom.DraggableAreaRect.y < -.5f)
            {
                proCamera2DPanAndZoom.DraggableAreaRect.y = -.5f;
            }

            if (proCamera2DPanAndZoom.DraggableAreaRect.y > .5f)
            {
                proCamera2DPanAndZoom.DraggableAreaRect.y = .5f;
            }

            // Warning
            if (!proCamera2DPanAndZoom.AllowPan && !proCamera2DPanAndZoom.AllowZoom)
            {
                EditorGUILayout.HelpBox("This won't be the most useful extension now, will it?", MessageType.Warning, true);
            }
        }
Exemplo n.º 11
0
        public override void OnInspectorGUI()
        {
            if (target == null)
            {
                return;
            }

            var proCamera2DPixelPerfect = (ProCamera2DPixelPerfect)target;

            if (proCamera2DPixelPerfect.ProCamera2D == null)
            {
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);
                return;
            }

            var isOrthographic = proCamera2DPixelPerfect.ProCamera2D.GameCamera.orthographic;

            if (!isOrthographic)
            {
                EditorGUILayout.HelpBox("Pixel perfect only works with orthographic cameras!", MessageType.Error, true);
            }

            serializedObject.Update();

            // Show script link
            GUI.enabled = false;
            _script     = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;
            GUI.enabled = true;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("_pc2D"), _tooltip);

            EditorGUI.BeginChangeCheck();

            // Pixels per unit
            _tooltip = new GUIContent("Pixels per Unit", "How many pixels in a sprite correspond to one unit in the world");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("PixelsPerUnit"), _tooltip);

            // Viewport auto-scale
            EditorGUILayout.BeginHorizontal();

            _tooltip = new GUIContent("Viewport AutoScale", "If not None, the camera will automatically calculate the best scale across all resolutions based on the art viewport.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ViewportAutoScale"), _tooltip);

            // Viewport Scale
            if (proCamera2DPixelPerfect.ViewportAutoScale != AutoScaleMode.None)
            {
                GUI.enabled = false;
                EditorGUILayout.LabelField(proCamera2DPixelPerfect.CalculateViewportScale() + "x", GUILayout.MaxWidth(60));
                GUI.enabled = true;
            }

            EditorGUILayout.EndHorizontal();

            // Viewport size in pixels
            if (proCamera2DPixelPerfect.ViewportAutoScale != AutoScaleMode.None)
            {
                _tooltip = new GUIContent("Game Viewport (pixels)", "Set it that if the screen was of this size, each pixel on the screen would correspond to a pixel on your art. On a pixel-art game this probably has low values.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("TargetViewportSizeInPixels"), _tooltip);
            }

            // Zoom
            _tooltip = new GUIContent("Zoom", "The zoom level of the camera");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("_zoom"), _tooltip);

            // Snap movement to grid
            EditorGUILayout.BeginHorizontal();
            _tooltip = new GUIContent("Snap Movement to Grid", "If checked, the the sprites will snap to the grid. Might create some stuttering on your camera targets, especially if you're using a large grid and a follow smoothness greater than zero.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("SnapMovementToGrid"), _tooltip);

            if (proCamera2DPixelPerfect.SnapMovementToGrid)
            {
                _tooltip = new GUIContent("Snap Camera", "If checked, the camera will also snap to the grid. If you notice some stuttering in your game elements try to leave this on.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("SnapCameraToGrid"), _tooltip);
            }
            EditorGUILayout.EndHorizontal();

            // Draw grid
            EditorGUILayout.BeginHorizontal();

            _tooltip = new GUIContent("Draw Grid", "If checked, the camera will draw a pixel grid. 'Gizmos' button must be enabled on the Game window.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("DrawGrid"), _tooltip);

            if (proCamera2DPixelPerfect.DrawGrid)
            {
                _tooltip = new GUIContent("Grid Color", "");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("GridColor"), _tooltip);
            }

            EditorGUILayout.EndHorizontal();

            // Grid density warning
            if (proCamera2DPixelPerfect.DrawGrid && proCamera2DPixelPerfect.GridDensity < 4)
            {
                EditorGUILayout.HelpBox("Grid density is too high to draw, so we're skipping it to avoid performance issues with the editor.", MessageType.None, true);
            }

            // Save properties
            serializedObject.ApplyModifiedProperties();

            // Limit values
            if (proCamera2DPixelPerfect.PixelsPerUnit < 1f)
            {
                proCamera2DPixelPerfect.PixelsPerUnit = 1f;
            }

            if (proCamera2DPixelPerfect.TargetViewportSizeInPixels.x < 1)
            {
                proCamera2DPixelPerfect.TargetViewportSizeInPixels.x = 1;
            }

            if (proCamera2DPixelPerfect.TargetViewportSizeInPixels.y < 1)
            {
                proCamera2DPixelPerfect.TargetViewportSizeInPixels.y = 1;
            }

            // Resize camera
            if (EditorGUI.EndChangeCheck() || !Application.isPlaying)
            {
                proCamera2DPixelPerfect.ResizeCameraToPixelPerfect();
            }
        }
Exemplo n.º 12
0
        /// <returns>Returns a dictionary of type name inside MRTK DLLs mapped to additional data.</returns>
        private static Dictionary <string, ClassInformation> ProcessCompiledDLLs(string temporaryDirectoryName, string outputDirectory, Dictionary <string, string> asmDefMappings)
        {
            Assembly[] dlls = CompilationPipeline.GetAssemblies();

            string tmpDirPath = Path.Combine(Application.dataPath, temporaryDirectoryName);

            if (Directory.Exists(tmpDirPath))
            {
                Directory.Delete(tmpDirPath);
            }

            Directory.CreateDirectory(tmpDirPath);

            try
            {
                foreach (Assembly dll in dlls)
                {
                    if (dll.name.Contains("MixedReality"))
                    {
                        File.Copy(dll.outputPath, Path.Combine(tmpDirPath, $"{dll.name}.dll"), true);
                    }
                }

                // Load these directories
                AssetDatabase.Refresh();

                Dictionary <string, ClassInformation> toReturn = new Dictionary <string, ClassInformation>();

                if (Directory.Exists(outputDirectory))
                {
                    Directory.Delete(outputDirectory, true);
                }

                Directory.CreateDirectory(outputDirectory);
                foreach (Assembly dll in dlls)
                {
                    if (dll.name.Contains("MixedReality"))
                    {
                        if (!asmDefMappings.TryGetValue($"{dll.name}.dll", out string newDllGuid))
                        {
                            throw new InvalidOperationException($"No guid based on .asmdef was generated for DLL '{dll.name}'.");
                        }

                        File.Copy(Path.Combine(tmpDirPath, $"{dll.name}.dll"), Path.Combine(outputDirectory, $"{dll.name}.dll"));
                        File.Copy(Path.Combine(tmpDirPath, $"{dll.name}.dll.meta"), Path.Combine(outputDirectory, $"{dll.name}.dll.meta"));

                        Object[] assets = AssetDatabase.LoadAllAssetsAtPath(Path.Combine("Assets", temporaryDirectoryName, $"{dll.name}.dll"));

                        foreach (Object asset in assets)
                        {
                            MonoScript monoScript = asset as MonoScript;
                            if (!(monoScript is null) && AssetDatabase.TryGetGUIDAndLocalFileIdentifier(monoScript, out string guid, out long fileId))
                            {
                                Type type = monoScript.GetClass();

                                if (type.Namespace == null || !type.Namespace.Contains("Microsoft.MixedReality.Toolkit"))
                                {
                                    throw new InvalidDataException($"Type {type.Name} is not a member of the Microsoft.MixedReality.Toolkit namespace");
                                }
                                toReturn.Add(type.FullName, new ClassInformation()
                                {
                                    Name = type.Name, Namespace = type.Namespace, FileId = fileId, Guid = newDllGuid
                                });
                            }
                        }
                    }
                }

                return(toReturn);
            }
            finally
            {
                Directory.Delete(tmpDirPath, true);
                AssetDatabase.Refresh();
            }
        }
Exemplo n.º 13
0
    private static void SortDependencies_Visit_VisitDependency(HashSet <MonoScript> visited, List <MonoScript> sortedItems, Dictionary <Type, MonoScript> lookup,
                                                               Dictionary <MonoScript, HashSet <MonoScript> > connections, Type depType, MonoScript visitedFrom, bool fixedOrderDeps, bool leafDeps)
    {
        if (depType == null)
        {
            return;
        }

        if (!typeof(ScriptableObject).IsAssignableFrom(depType) &&
            !typeof(MonoBehaviour).IsAssignableFrom(depType))
        {
            return;
        }

        MonoScript depScript = null;

        if (!lookup.TryGetValue(depType, out depScript))
        {
            Debug.LogError("ScriptDependency type " + depType.Name + " not found found for script " + visitedFrom.name +
                           "! Check that it exists in a file with the same name as the class");
            return;
        }

        if (fixedOrderDeps && !HasFixedOrder(depScript))
        {
            return;
        }

        HashSet <MonoScript> connectionSet = null;

        if (leafDeps &&
            connections.TryGetValue(depScript, out connectionSet) &&
            GetScriptDependencies(depScript).Length != connectionSet.Count)
        {
            return;
        }

        if (lookup.TryGetValue(depType, out depScript) /* && !HasFixedOrder(depScript)*/)
        {
            SortDependencies_Visit(depScript, visited, sortedItems, lookup, visitedFrom, connections);
        }
    }
Exemplo n.º 14
0
    /// <summary>
    /// Sort the scripts by dependencies
    /// </summary>
    static List <IslandItem[]> SortDependencies(UnityEditor.MonoScript[] scriptsToSort)
    {
        var lookup      = new Dictionary <Type, UnityEditor.MonoScript>();
        var visited     = new HashSet <UnityEditor.MonoScript>();
        var sortedItems = new List <UnityEditor.MonoScript>();
        var connections = new Dictionary <UnityEditor.MonoScript, HashSet <UnityEditor.MonoScript> >();

        // add everything to lookup
        for (int i = 0; i < scriptsToSort.Length; ++i)
        {
            var script = scriptsToSort[i];
            if (script == null)
            {
                continue;
            }
            lookup[script.GetClass()] = script;
        }

        // build connection graph
        for (int i = 0; i < scriptsToSort.Length; ++i)
        {
            var script = scriptsToSort[i];
            if (script == null)
            {
                continue;
            }
            if (!HasDependencies(script))
            {
                continue;
            }
            var deps = GetScriptDependencies(scriptsToSort[i]);
            for (int j = 0; j < deps.Length; ++j)
            {
                var depType = deps[j];
                if (depType == null)
                {
                    continue;
                }

                MonoScript depScript = null;
                if (!lookup.TryGetValue(depType, out depScript))
                {
                    continue;
                }

                // forward
                HashSet <UnityEditor.MonoScript> forwardSet = null;
                if (!connections.TryGetValue(script, out forwardSet))
                {
                    connections[script] = forwardSet = new HashSet <MonoScript>();
                }
                forwardSet.Add(depScript);

                // reverse
                HashSet <UnityEditor.MonoScript> reverseSet = null;
                if (!connections.TryGetValue(depScript, out reverseSet))
                {
                    connections[depScript] = reverseSet = new HashSet <MonoScript>();
                }
                reverseSet.Add(script);
            }
        }

        // sort fixed order items first
        for (int i = 0; i < scriptsToSort.Length; ++i)
        {
            var script = scriptsToSort[i];
            if (script == null || !HasDependencies(script))
            {
                continue;
            }
            if (!HasFixedOrder(script))
            {
                continue;
            }
            SortDependencies_Visit(script, visited, sortedItems, lookup, null, connections);
        }

        // non-leaves
        for (int i = 0; i < scriptsToSort.Length; ++i)
        {
            var script = scriptsToSort[i];
            if (script == null || !HasDependencies(script))
            {
                continue;
            }

            HashSet <MonoScript> connectionSet = null;
            if (connections.TryGetValue(script, out connectionSet) &&
                GetScriptDependencies(script).Length == connections[script].Count)
            {
                continue;
            }

            SortDependencies_Visit(script, visited, sortedItems, lookup, null, connections);
        }

        // leaves (any that remain)
        for (int i = 0; i < scriptsToSort.Length; ++i)
        {
            var script = scriptsToSort[i];
            if (script == null || !HasDependencies(script))
            {
                continue;
            }
            SortDependencies_Visit(script, visited, sortedItems, lookup, null, connections);
        }


        //Debug.Log("ScriptExecutionOrder: Sorted dependencies: "+string.Join(", ",sortedItems.Select(x=>x.name).ToArray()));
        return(SortDependencies_CreateGraphIslands(sortedItems, connections));
    }
        public override void OnInspectorGUI()
        {
            if (target == null)
            {
                return;
            }

            var proCamera2DLimitDistance = (ProCamera2DLimitDistance)target;

            serializedObject.Update();

            // Show script link
            GUI.enabled = false;
            _script     = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;
            GUI.enabled = true;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("_pc2D"), _tooltip);

            if (proCamera2DLimitDistance.ProCamera2D == null)
            {
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);
            }

            // Use Targets Position
            EditorGUILayout.Space();
            _tooltip = new GUIContent("Use Targets Position", "If enabled, the extension will use the targets midpoint instead of the camera center for calculations.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("UseTargetsPosition"), _tooltip);
            EditorGUILayout.Space();

            // Limits
            DrawGUI(
                "Limit Top Distance",
                "Prevent the camera target from getting out of the screen. Use this if you have a high follow smoothness and your targets are getting out of the screen.",
                "LimitTopCameraDistance",
                proCamera2DLimitDistance.LimitTopCameraDistance,
                "MaxTopTargetDistance");

            DrawGUI(
                "Limit Bottom Distance",
                "Prevent the camera target from getting out of the screen. Use this if you have a high follow smoothness and your targets are getting out of the screen.",
                "LimitBottomCameraDistance",
                proCamera2DLimitDistance.LimitBottomCameraDistance,
                "MaxBottomTargetDistance");

            DrawGUI(
                "Limit Left Distance",
                "Prevent the camera target from getting out of the screen. Use this if you have a high follow smoothness and your targets are getting out of the screen.",
                "LimitLeftCameraDistance",
                proCamera2DLimitDistance.LimitLeftCameraDistance,
                "MaxLeftTargetDistance");

            DrawGUI(
                "Limit Right Distance",
                "Prevent the camera target from getting out of the screen. Use this if you have a high follow smoothness and your targets are getting out of the screen.",
                "LimitRightCameraDistance",
                proCamera2DLimitDistance.LimitRightCameraDistance,
                "MaxRightTargetDistance");

            serializedObject.ApplyModifiedProperties();
        }
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);
        var type = GetFieldType();

        if (type == null || ignoreClassFullNames.Contains(type.FullName))
        {
            EditorGUI.PropertyField(position, property, label);
            EditorGUI.EndProperty();
            return;
        }

        ScriptableObject propertySO = null;

        if (!property.hasMultipleDifferentValues && property.serializedObject.targetObject != null && property.serializedObject.targetObject is ScriptableObject)
        {
            propertySO = (ScriptableObject)property.serializedObject.targetObject;
        }

        var propertyRect = Rect.zero;
        var guiContent   = new GUIContent(property.displayName);
        var foldoutRect  = new Rect(position.x, position.y, EditorGUIUtility.labelWidth, EditorGUIUtility.singleLineHeight);

        if (property.objectReferenceValue != null && AreAnySubPropertiesVisible(property))
        {
            property.isExpanded = EditorGUI.Foldout(foldoutRect, property.isExpanded, guiContent, true);
        }
        else
        {
            // So yeah having a foldout look like a label is a weird hack
            // but both code paths seem to need to be a foldout or
            // the object field control goes weird when the codepath changes.
            // I guess because foldout is an interactable control of its own and throws off the controlID?
            foldoutRect.x += 12;
            EditorGUI.Foldout(foldoutRect, property.isExpanded, guiContent, true, EditorStyles.label);
        }
        var indentedPosition = EditorGUI.IndentedRect(position);
        var indentOffset     = indentedPosition.x - position.x;

        propertyRect = new Rect(position.x + (EditorGUIUtility.labelWidth - indentOffset), position.y, position.width - (EditorGUIUtility.labelWidth - indentOffset), EditorGUIUtility.singleLineHeight);

        if (propertySO != null || property.objectReferenceValue == null)
        {
            propertyRect.width -= buttonWidth;
        }

        EditorGUI.ObjectField(propertyRect, property, type, GUIContent.none);
        if (GUI.changed)
        {
            property.serializedObject.ApplyModifiedProperties();
        }

        var buttonRect = new Rect(position.x + position.width - buttonWidth, position.y, buttonWidth, EditorGUIUtility.singleLineHeight);

        if (property.propertyType == SerializedPropertyType.ObjectReference && property.objectReferenceValue != null)
        {
            var data = (ScriptableObject)property.objectReferenceValue;

            if (property.isExpanded)
            {
                // Draw a background that shows us clearly which fields are part of the ScriptableObject
                GUI.Box(new Rect(0, position.y + EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing - 1, Screen.width, position.height - EditorGUIUtility.singleLineHeight - EditorGUIUtility.standardVerticalSpacing), "");

                EditorGUI.indentLevel++;
                SerializedObject serializedObject = new SerializedObject(data);

                // Iterate over all the values and draw them
                SerializedProperty prop = serializedObject.GetIterator();
                float y = position.y + EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
                if (prop.NextVisible(true))
                {
                    do
                    {
                        // Don't bother drawing the class file
                        if (prop.name == "m_Script")
                        {
                            continue;
                        }
                        float height = EditorGUI.GetPropertyHeight(prop, new GUIContent(prop.displayName), true);
                        EditorGUI.PropertyField(new Rect(position.x, y, position.width - buttonWidth, height), prop, true);
                        y += height + EditorGUIUtility.standardVerticalSpacing;
                    }while (prop.NextVisible(false));
                }
                if (GUI.changed)
                {
                    serializedObject.ApplyModifiedProperties();
                }

                EditorGUI.indentLevel--;
            }
        }
        else
        {
            if (GUI.Button(buttonRect, "Create"))
            {
                string selectedAssetPath = "Assets";
                if (property.serializedObject.targetObject is MonoBehaviour)
                {
                    MonoScript ms = MonoScript.FromMonoBehaviour((MonoBehaviour)property.serializedObject.targetObject);
                    selectedAssetPath = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(ms));
                }

                property.objectReferenceValue = CreateAssetWithSavePrompt(type, selectedAssetPath);
            }
        }
        property.serializedObject.ApplyModifiedProperties();
        EditorGUI.EndProperty();
    }
Exemplo n.º 17
0
        public override void OnInspectorGUI()
        {
            if (target == null)
            {
                return;
            }

            var proCamera2DRooms = (ProCamera2DRooms)target;

            if (proCamera2DRooms.ProCamera2D == null)
            {
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);
                return;
            }

            serializedObject.Update();

            // Show script link
            GUI.enabled = false;
            _script     = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;
            GUI.enabled = true;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("_pc2D"), _tooltip);
            EditorGUILayout.Space();

            // Rooms List
            _roomsList.DoLayoutList();
            EditorGUILayout.Space();
            EditorGUILayout.Space();

            // Update interval
            _tooltip = new GUIContent("Update Interval", "Every X seconds detect collision. Smaller frequencies are more precise but also require more processing.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("UpdateInterval"), _tooltip);

            if (proCamera2DRooms.UpdateInterval <= 0.01f)
            {
                proCamera2DRooms.UpdateInterval = 0.01f;
            }

            // Trigger targets
            EditorGUILayout.BeginHorizontal();
            _tooltip = new GUIContent("Use Targets Mid Point", "If checked, the trigger will use the mid point of all your camera targets");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("UseTargetsMidPoint"), _tooltip);

            if (!proCamera2DRooms.UseTargetsMidPoint)
            {
                _tooltip = new GUIContent("Trigger Target", "The target to use instead of the mid point of all camera targets");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("TriggerTarget"), _tooltip);
            }
            EditorGUILayout.EndHorizontal();

            // Transition instanly on start
            _tooltip = new GUIContent("Transition Instanly On Start", "If checked, the camera will instantly transition to the current room on start");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("TransitionInstanlyOnStart"), _tooltip);

            // Restore on room exit
            _tooltip = new GUIContent("Restore On Room Exit", "If checked, the camera will restore its initial settings when not in any room");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("RestoreOnRoomExit"), _tooltip);

            if (proCamera2DRooms.RestoreOnRoomExit)
            {
                EditorGUI.indentLevel = 1;

                // Restore duration
                _tooltip = new GUIContent("Restore Duration", "How long it takes to restore the original settings");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("RestoreDuration"), _tooltip);

                // Restore ease type
                _tooltip = new GUIContent("Restore Ease Type", "The ease type of the restore animation");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("RestoreEaseType"), _tooltip);

                EditorGUI.indentLevel = 0;
            }

            // Automatic room detection
            _tooltip = new GUIContent("Automatic Room Activation", "If checked, ProCamera2D will automatically transition to the rooms based on the target(s) position. If disabled, you have to manually call the method EnterRoom(roomID)");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("AutomaticRoomActivation"), _tooltip);

            // Use relative position - Option only visible if the gameobject is not the ProCamera2D container
            if (proCamera2DRooms.GetComponent <ProCamera2D>() == null)
            {
                _tooltip = new GUIContent("Use Relative Positioning", "If checked, the rooms positions are relative to the containing GameObject");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("UseRelativePosition"), _tooltip);
            }
            else
            {
                GUI.enabled = false;
                _tooltip    = new GUIContent("Use Relative Positioning", "If checked, the rooms positions are relative to the containing GameObject. Only supported if the Rooms extension is on a GameObject different than the ProCamera2D core component");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("UseRelativePosition"), _tooltip);
                GUI.enabled = true;
            }

            EditorGUILayout.Space();

            // Transition started event
            _tooltip = new GUIContent("OnStartedTransition", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("OnStartedTransition"), _tooltip);

            // Transition started event
            _tooltip = new GUIContent("OnFinishedTransition", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("OnFinishedTransition"), _tooltip);

            // Exited all rooms event
            _tooltip = new GUIContent("OnExitedAllRooms", "This event fires when the camera target is not currently on any room");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("OnExitedAllRooms"), _tooltip);

            // Apply modified properties
            serializedObject.ApplyModifiedProperties();
        }
    void OnGUI()
    {
        GUILayout.Label(position + "");
        GUILayout.Space(3);
        int oldValue = GUI.skin.window.padding.bottom;

        GUI.skin.window.padding.bottom = -20;
        Rect windowRect = GUILayoutUtility.GetRect(1, 17);

        windowRect.x     += 4;
        windowRect.width -= 7;
        editorMode        = GUI.SelectionGrid(windowRect, editorMode, modes, 2, "Window");
        GUI.skin.window.padding.bottom = oldValue;

        switch (editorMode)
        {
        case 0:
            selectedCheckType = GUILayout.SelectionGrid(selectedCheckType, checkType, 2, "Toggle");
            recursionVal      = GUILayout.Toggle(recursionVal, "Search all dependencies");
            GUI.enabled       = selectedCheckType == 0;
            targetComponent   = (MonoScript)EditorGUILayout.ObjectField(targetComponent, typeof(MonoScript), false);
            GUI.enabled       = true;

            if (GUILayout.Button("Check component usage"))
            {
                AssetDatabase.SaveAssets();
                switch (selectedCheckType)
                {
                case 0:
                    componentName = targetComponent.name;
                    string   targetPath = AssetDatabase.GetAssetPath(targetComponent);
                    string[] allPrefabs = GetAllPrefabs();
                    listResult = new List <string>();
                    foreach (string prefab in allPrefabs)
                    {
                        string[] single       = new string[] { prefab };
                        string[] dependencies = AssetDatabase.GetDependencies(single, recursionVal);
                        foreach (string dependedAsset in dependencies)
                        {
                            if (dependedAsset == targetPath)
                            {
                                listResult.Add(prefab);
                            }
                        }
                    }
                    break;

                case 1:
                    List <string> scenesToLoad = new List <string>();
                    existingComponents = new List <ComponentNames>();
                    prefabComponents   = new List <ComponentNames>();
                    notUsedComponents  = new List <ComponentNames>();
                    addedComponents    = new List <ComponentNames>();
                    sceneComponents    = new List <ComponentNames>();

                    if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                    {
                        string projectPath = Application.dataPath;
                        projectPath = projectPath.Substring(0, projectPath.IndexOf("Assets"));

                        string[] allAssets = AssetDatabase.GetAllAssetPaths();

                        foreach (string asset in allAssets)
                        {
                            int indexCS = asset.IndexOf(".cs");
                            int indexJS = asset.IndexOf(".js");
                            if (indexCS != -1 || indexJS != -1)
                            {
                                ComponentNames newComponent = new ComponentNames(NameFromPath(asset), "", asset);
                                try
                                {
                                    System.IO.FileStream   FS = new System.IO.FileStream(projectPath + asset, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                                    System.IO.StreamReader SR = new System.IO.StreamReader(FS);
                                    string line;
                                    while (!SR.EndOfStream)
                                    {
                                        line = SR.ReadLine();
                                        int index1 = line.IndexOf("namespace");
                                        int index2 = line.IndexOf("{");
                                        if (index1 != -1 && index2 != -1)
                                        {
                                            line   = line.Substring(index1 + 9);
                                            index2 = line.IndexOf("{");
                                            line   = line.Substring(0, index2);
                                            line   = line.Replace(" ", "");
                                            newComponent.namespaceName = line;
                                        }
                                    }
                                }
                                catch
                                {
                                }

                                existingComponents.Add(newComponent);

                                try
                                {
                                    System.IO.FileStream   FS = new System.IO.FileStream(projectPath + asset, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                                    System.IO.StreamReader SR = new System.IO.StreamReader(FS);

                                    string line;
                                    int    lineNum = 0;
                                    while (!SR.EndOfStream)
                                    {
                                        lineNum++;
                                        line = SR.ReadLine();
                                        int index = line.IndexOf("AddComponent");
                                        if (index != -1)
                                        {
                                            line = line.Substring(index + 12);
                                            if (line[0] == '(')
                                            {
                                                line = line.Substring(1, line.IndexOf(')') - 1);
                                            }
                                            else if (line[0] == '<')
                                            {
                                                line = line.Substring(1, line.IndexOf('>') - 1);
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                            line  = line.Replace(" ", "");
                                            line  = line.Replace("\"", "");
                                            index = line.LastIndexOf('.');
                                            ComponentNames newComp;
                                            if (index == -1)
                                            {
                                                newComp = new ComponentNames(line, "", "");
                                            }
                                            else
                                            {
                                                newComp = new ComponentNames(line.Substring(index + 1, line.Length - (index + 1)), line.Substring(0, index), "");
                                            }
                                            string pName = asset + ", Line " + lineNum;
                                            newComp.usageSource.Add(pName);
                                            index = addedComponents.IndexOf(newComp);
                                            if (index == -1)
                                            {
                                                addedComponents.Add(newComp);
                                            }
                                            else
                                            {
                                                if (!addedComponents[index].usageSource.Contains(pName))
                                                {
                                                    addedComponents[index].usageSource.Add(pName);
                                                }
                                            }
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                            int indexPrefab = asset.IndexOf(".prefab");

                            if (indexPrefab != -1)
                            {
                                string[] single       = new string[] { asset };
                                string[] dependencies = AssetDatabase.GetDependencies(single, recursionVal);
                                foreach (string dependedAsset in dependencies)
                                {
                                    if (dependedAsset.IndexOf(".cs") != -1 || dependedAsset.IndexOf(".js") != -1)
                                    {
                                        ComponentNames newComponent = new ComponentNames(NameFromPath(dependedAsset), GetNamespaceFromPath(dependedAsset), dependedAsset);
                                        int            index        = prefabComponents.IndexOf(newComponent);
                                        if (index == -1)
                                        {
                                            newComponent.usageSource.Add(asset);
                                            prefabComponents.Add(newComponent);
                                        }
                                        else
                                        {
                                            if (!prefabComponents[index].usageSource.Contains(asset))
                                            {
                                                prefabComponents[index].usageSource.Add(asset);
                                            }
                                        }
                                    }
                                }
                            }
                            int indexUnity = asset.IndexOf(".unity");
                            if (indexUnity != -1)
                            {
                                scenesToLoad.Add(asset);
                            }
                        }

                        for (int i = addedComponents.Count - 1; i > -1; i--)
                        {
                            addedComponents[i].assetPath = GetPathFromNames(addedComponents[i].namespaceName, addedComponents[i].componentName);
                            if (addedComponents[i].assetPath == "")
                            {
                                addedComponents.RemoveAt(i);
                            }
                        }

                        foreach (string scene in scenesToLoad)
                        {
                            EditorSceneManager.OpenScene(scene);
                            GameObject[] sceneGOs = GetAllObjectsInScene();
                            foreach (GameObject g in sceneGOs)
                            {
                                Component[] comps = g.GetComponentsInChildren <Component>(true);
                                foreach (Component c in comps)
                                {
                                    if (c != null && c.GetType() != null && c.GetType().BaseType != null && c.GetType().BaseType == typeof(MonoBehaviour))
                                    {
                                        SerializedObject   so      = new SerializedObject(c);
                                        SerializedProperty p       = so.FindProperty("m_Script");
                                        string             path    = AssetDatabase.GetAssetPath(p.objectReferenceValue);
                                        ComponentNames     newComp = new ComponentNames(NameFromPath(path), GetNamespaceFromPath(path), path);
                                        newComp.usageSource.Add(scene);
                                        int index = sceneComponents.IndexOf(newComp);
                                        if (index == -1)
                                        {
                                            sceneComponents.Add(newComp);
                                        }
                                        else
                                        {
                                            if (!sceneComponents[index].usageSource.Contains(scene))
                                            {
                                                sceneComponents[index].usageSource.Add(scene);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        foreach (ComponentNames c in existingComponents)
                        {
                            if (addedComponents.Contains(c))
                            {
                                continue;
                            }
                            if (prefabComponents.Contains(c))
                            {
                                continue;
                            }
                            if (sceneComponents.Contains(c))
                            {
                                continue;
                            }
                            notUsedComponents.Add(c);
                        }

                        addedComponents.Sort(SortAlphabetically);
                        prefabComponents.Sort(SortAlphabetically);
                        sceneComponents.Sort(SortAlphabetically);
                        notUsedComponents.Sort(SortAlphabetically);
                    }
                    break;
                }
            }
            break;

        case 1:
            if (GUILayout.Button("Search!"))
            {
                string[] allPrefabs = GetAllPrefabs();
                listResult = new List <string>();
                foreach (string prefab in allPrefabs)
                {
                    UnityEngine.Object o = AssetDatabase.LoadMainAssetAtPath(prefab);
                    GameObject         go;
                    try
                    {
                        go = (GameObject)o;
                        Component[] components = go.GetComponentsInChildren <Component>(true);
                        foreach (Component c in components)
                        {
                            if (c == null)
                            {
                                listResult.Add(prefab);
                            }
                        }
                    }
                    catch
                    {
                        Debug.Log("For some reason, prefab " + prefab + " won't cast to GameObject");
                    }
                }
            }
            break;
        }
        if (editorMode == 1 || selectedCheckType == 0)
        {
            if (listResult != null)
            {
                if (listResult.Count == 0)
                {
                    GUILayout.Label(editorMode == 0 ? (componentName == "" ? "Choose a component" : "No prefabs use component " + componentName) : ("No prefabs have missing components!\nClick Search to check again"));
                }
                else
                {
                    GUILayout.Label(editorMode == 0 ? ("The following " + listResult.Count + " prefabs use component " + componentName + ":") : ("The following prefabs have missing components:"));
                    scroll = GUILayout.BeginScrollView(scroll);
                    foreach (string s in listResult)
                    {
                        GUILayout.BeginHorizontal();
                        GUILayout.Label(s, GUILayout.Width(position.width / 2));
                        if (GUILayout.Button("Select", GUILayout.Width(position.width / 2 - 10)))
                        {
                            Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(s);
                        }
                        GUILayout.EndHorizontal();
                    }
                    GUILayout.EndScrollView();
                }
            }
        }
        else
        {
            showPrefabs = GUILayout.Toggle(showPrefabs, "Show prefab components");
            if (showPrefabs)
            {
                GUILayout.Label("The following components are attatched to prefabs:");
                DisplayResults(ref scroll1, ref prefabComponents);
            }
            showAdded = GUILayout.Toggle(showAdded, "Show AddComponent arguments");
            if (showAdded)
            {
                GUILayout.Label("The following components are AddComponent arguments:");
                DisplayResults(ref scroll2, ref addedComponents);
            }
            showScene = GUILayout.Toggle(showScene, "Show Scene-used components");
            if (showScene)
            {
                GUILayout.Label("The following components are used by scene objects:");
                DisplayResults(ref scroll3, ref sceneComponents);
            }
            showUnused = GUILayout.Toggle(showUnused, "Show Unused Components");
            if (showUnused)
            {
                GUILayout.Label("The following components are not used by prefabs, by AddComponent, OR in any scene:");
                DisplayResults(ref scroll4, ref notUsedComponents);
            }
        }
    }
Exemplo n.º 19
0
        private void OnEnable()
        {
            _editor = this;
            FolderManager.Initialize();

            FolderManager.ClientRepaints -= Repaint;
            FolderManager.ClientRepaints += Repaint;

            SceneView.onSceneGUIDelegate -= OnSceneGUI;
            SceneView.onSceneGUIDelegate += OnSceneGUI;

            FolderManagerCallbacks.OnAddElement -= ElementAdded;
            FolderManagerCallbacks.OnAddElement += ElementAdded;

            FolderManagerCallbacks.OnDeleteElement -= ElementAdded;
            FolderManagerCallbacks.OnDeleteElement += ElementAdded;

            Cache = new FolderTreeCache(DirectoryUtility.GetDirectoryName(AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this))));
            Cache.SetupCacheEvents();
        }
Exemplo n.º 20
0
        private void HeaderBoxMain(string title, ref bool drawGizmos, ref bool defaultInspector, Texture2D scrIcon, MonoBehaviour target, int height = 22)
        {
            EditorGUILayout.BeginVertical(FGUI_Resources.HeaderBoxStyle);

            EditorGUILayout.BeginHorizontal();

            if (GUILayout.Button(new GUIContent(scrIcon), EditorStyles.label, new GUILayoutOption[2] {
                GUILayout.Width(height - 2), GUILayout.Height(height - 2)
            }))
            {
                MonoScript script = MonoScript.FromMonoBehaviour(target);
                if (script)
                {
                    EditorGUIUtility.PingObject(script);
                }
                drawHeaderFoldout = !drawHeaderFoldout;
            }

            if (GUILayout.Button(title, FGUI_Resources.GetTextStyle(14, true, TextAnchor.MiddleLeft), GUILayout.Height(height)))
            {
                MonoScript script = MonoScript.FromMonoBehaviour(target);
                if (script)
                {
                    EditorGUIUtility.PingObject(script);
                }
                drawHeaderFoldout = !drawHeaderFoldout;
            }

            if (EditorGUIUtility.currentViewWidth > 326)
            {
                // Youtube channel button
                if (GUILayout.Button(new GUIContent(FGUI_Resources.Tex_Tutorials, "Open FImpossible Creations Channel with tutorial videos in your web browser"), FGUI_Resources.ButtonStyle, new GUILayoutOption[2] {
                    GUILayout.Width(height), GUILayout.Height(height)
                }))
                {
                    Application.OpenURL("https://www.youtube.com/c/FImpossibleCreations");
                }
            }

            if (EditorGUIUtility.currentViewWidth > 292)
            {
                // Store site button
                if (GUILayout.Button(new GUIContent(FGUI_Resources.Tex_Website, "Open FImpossible Creations Asset Store Page inside your web browser"), FGUI_Resources.ButtonStyle, new GUILayoutOption[2] {
                    GUILayout.Width(height), GUILayout.Height(height)
                }))
                {
                    Application.OpenURL("https://assetstore.unity.com/publishers/37262");
                }
            }

            // Manual file button
            if (_manualFile == null)
            {
                _manualFile = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(MonoScript.FromMonoBehaviour(target))) + "/Look Animator User Manual.pdf");
            }
            if (_manualFile)
            {
                if (GUILayout.Button(new GUIContent(FGUI_Resources.Tex_Manual, "Open .PDF user manual file for Look Animator"), FGUI_Resources.ButtonStyle, new GUILayoutOption[2] {
                    GUILayout.Width(height), GUILayout.Height(height)
                }))
                {
                    EditorGUIUtility.PingObject(_manualFile);
                    Application.OpenURL(Application.dataPath + "/" + AssetDatabase.GetAssetPath(_manualFile).Replace("Assets/", ""));
                }
            }

            FGUI_Inspector.DrawSwitchButton(ref drawGizmos, FGUI_Resources.Tex_GizmosOff, FGUI_Resources.Tex_Gizmos, "Toggle drawing gizmos on character in scene window", height, height, true);
            FGUI_Inspector.DrawSwitchButton(ref drawHeaderFoldout, FGUI_Resources.Tex_LeftFold, FGUI_Resources.Tex_DownFold, "Toggle to view additional options for foldouts", height, height);

            EditorGUILayout.EndHorizontal();

            if (drawHeaderFoldout)
            {
                FGUI_Inspector.DrawUILine(0.07f, 0.1f, 1, 4, 0.99f);

                EditorGUILayout.BeginHorizontal();

                EditorGUI.BeginChangeCheck();
                choosedLang = (ELangs)EditorGUILayout.EnumPopup(choosedLang, new GUIStyle(EditorStyles.layerMaskField)
                {
                    fixedHeight = 0
                }, new GUILayoutOption[2] {
                    GUILayout.Width(80), GUILayout.Height(22)
                });
                if (EditorGUI.EndChangeCheck())
                {
                    PlayerPrefs.SetInt("FLookAnimLang", (int)choosedLang);
                    SetupLangs();
                }

                GUILayout.FlexibleSpace();

                bool hierSwitchOn = PlayerPrefs.GetInt("AnimsH", 1) == 1;
                FGUI_Inspector.DrawSwitchButton(ref hierSwitchOn, FGUI_Resources.Tex_HierSwitch, null, "Switch drawing small icons in hierarchy", height, height, true);
                PlayerPrefs.SetInt("AnimsH", hierSwitchOn ? 1 : 0);

                if (GUILayout.Button(new GUIContent(FGUI_Resources.Tex_Rename, "Change component title to yours (current: '" + Get._editor_displayName + "'"), FGUI_Resources.ButtonStyle, new GUILayoutOption[2] {
                    GUILayout.Width(height), GUILayout.Height(height)
                }))
                {
                    string filename = EditorUtility.SaveFilePanelInProject("Type your title (no file will be created)", Get._editor_displayName, "", "Type your title (no file will be created)");
                    if (!string.IsNullOrEmpty(filename))
                    {
                        filename = System.IO.Path.GetFileNameWithoutExtension(filename);
                        if (!string.IsNullOrEmpty(filename))
                        {
                            Get._editor_displayName = filename; serializedObject.ApplyModifiedProperties();
                        }
                    }
                }

                // Default inspector switch
                FGUI_Inspector.DrawSwitchButton(ref drawNewInspector, FGUI_Resources.Tex_AB, null, "Switch GUI Style to old / new", height, height, true);
                if (!drawNewInspector && drawDefaultInspector)
                {
                    drawDefaultInspector = false;
                }

                // Old new UI Button
                FGUI_Inspector.DrawSwitchButton(ref defaultInspector, FGUI_Resources.Tex_Default, null, "Toggle inspector view to default inspector.\n\nIf you ever edit source code of Look Animator and add custom variables, you can see them by entering this mode, also sometimes there can be additional/experimental variables to play with.", height, height);
                if (!drawNewInspector && drawDefaultInspector)
                {
                    drawNewInspector = false;
                }

                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.EndVertical();
        }
Exemplo n.º 21
0
 void Init(object _target)
 {
     Target = _target;
     Script = EditorExtension.FindScriptFromType(Target.GetType());
     Fields = ReflectionHelper.GetFieldInfos(Target.GetType()).Where(field => GUILayoutExtension.CanDraw(field)).ToList();
 }
Exemplo n.º 22
0
        public static MonoScript FindScriptFile([NotNull] Type classType)
        {
            string name = classType.Name;

            if (classType.IsGenericType)
            {
                // Parse out generic type information from generic type name
                int i = name.IndexOf('`');
                if (i != -1)
                {
                    name = name.Substring(0, i);
                }

                // Additionally, convert generic types to their generic type defitions.
                // E.g. List<string> to List<>.
                if (!classType.IsGenericTypeDefinition)
                {
                    classType = classType.GetGenericTypeDefinition();
                }
            }

            var guids = AssetDatabase.FindAssets(name + " t:MonoScript");

            int count = guids.Length;

            if (count == 0)
            {
                return(null);
            }

            MonoScript fallback = null;

            for (int n = count - 1; n >= 0; n--)
            {
                var guid     = guids[n];
                var path     = AssetDatabase.GUIDToAssetPath(guid);
                var filename = Path.GetFileNameWithoutExtension(path);
                if (string.Equals(filename, name, StringComparison.OrdinalIgnoreCase))
                {
                    var scriptAsset     = AssetDatabase.LoadAssetAtPath <MonoScript>(path);
                    var scriptClassType = scriptAsset.GetClass();
                    if (scriptClassType == classType)
                    {
                        return(scriptAsset);
                    }

                    if (scriptClassType == null)
                    {
                        fallback = scriptAsset;
                    }

                                        #if DEV_MODE
                    Debug.LogWarning("FindScriptFile(" + StringUtils.ToString(classType) + ") ignoring file @ \"" + path + "\" because MonoScript.GetClass() result " + StringUtils.ToStringSansNamespace(scriptClassType) + " did not match classType.");
                                        #endif
                }
            }

            // Second pass: test files where filename is only a partial match for class name.
            // E.g. class Header could be defined in file HeaderAttribute.cs.
            if (count > 1)
            {
                for (int n = count - 1; n >= 0; n--)
                {
                    var guid     = guids[n];
                    var path     = AssetDatabase.GUIDToAssetPath(guid);
                    var filename = Path.GetFileNameWithoutExtension(path);
                    if (!string.Equals(filename, name, StringComparison.OrdinalIgnoreCase))
                    {
                        var scriptAsset     = AssetDatabase.LoadAssetAtPath <MonoScript>(path);
                        var scriptClassType = scriptAsset.GetClass();
                        if (scriptClassType == classType)
                        {
                            return(scriptAsset);
                        }

                        if (fallback == null && scriptClassType == null)
                        {
                            fallback = scriptAsset;
                        }

                                                #if DEV_MODE
                        Debug.LogWarning("FindScriptFile(" + StringUtils.ToString(classType) + ") second pass: ignoring file @ \"" + path + "\" because MonoScript.GetClass() result " + StringUtils.ToStringSansNamespace(scriptClassType) + " did not match classType.");
                                                #endif
                    }
                }
            }

            // If was unable to verify correct script class type using MonoScript.GetClass()
            // but there was a probable match whose GetClass() returned null (seems to happen
            // with all generic types), then return that.
            if (fallback != null)
            {
                                #if DEV_MODE
                Debug.LogWarning("FindScriptFile(" + StringUtils.ToString(classType) + ") returning fallback result @ \"" + AssetDatabase.GetAssetPath(fallback) + "\".");
                                #endif
                return(fallback);
            }

                        #if DEV_MODE
            Debug.LogWarning("FindScriptFile(" + StringUtils.ToString(classType) + ") failed to find MonoScript for classType " + StringUtils.ToString(classType) + " AssetDatabase.FindAssets(\"" + name + " t:MonoScript\") returned " + count + " results: " + StringUtils.ToString(GuidsToAssetPaths(guids)));
                        #endif

            return(null);
        }
Exemplo n.º 23
0
    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        // Add clickable script field, as would have been provided by DrawDefaultInspector()
        MonoScript script = MonoScript.FromMonoBehaviour(target as MonoBehaviour);

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.ObjectField("Script", script, typeof(MonoScript), false);
        EditorGUI.EndDisabledGroup();

        CreateStylesAndContent();

        // Show all properties except for display state.
        EditorGUILayout.PropertyField(attachmentPrefabs, true);
        EditorGUILayout.PropertyField(touchPadColor);
        EditorGUILayout.PropertyField(appButtonColor);
        EditorGUILayout.PropertyField(systemButtonColor);
        EditorGUILayout.PropertyField(readControllerState);

        // Determine if the display state can currently be edited in the inspector.
        bool allowEditDisplayState = !readControllerState.boolValue || !Application.isPlaying;

        if (!allowEditDisplayState)
        {
            // Prevents editing the display state in the inspector.
            GUI.enabled = false;
        }

        Rect displayStateRect = EditorGUILayout.BeginVertical();

        GUI.Box(displayStateRect, "");

        // Show the display state header.
        EditorGUILayout.LabelField(displayStateHeaderContent,
                                   displayStateHeaderStyle,
                                   GUILayout.Height(displayStateHeaderHeight));

        // Indent the display state properties.
        EditorGUI.indentLevel++;

        // Iterate through the child properties of the displayState property.
        SerializedProperty iter        = displayState.Copy();
        SerializedProperty nextElement = displayState.Copy();
        bool hasNextElement            = nextElement.Next(false);

        iter.NextVisible(true);
        do
        {
            // It iter is the same as nextElement, then the iter has moved beyond the children of the
            // display state which means it has finished showing the display state.
            if (hasNextElement && SerializedProperty.EqualContents(nextElement, iter))
            {
                break;
            }

            GUIContent content = new GUIContent(DISPLAY_STATE_ITEM_PREFIX + iter.displayName);
            EditorGUILayout.PropertyField(iter, content);
        }while (iter.NextVisible(false));

        // End the vertical region and draw the box.
        EditorGUI.indentLevel--;
        EditorGUILayout.Space();
        EditorGUILayout.EndVertical();

        // Reset GUI.enabled.
        if (!allowEditDisplayState)
        {
            GUI.enabled = true;
        }

        EditorGUILayout.PropertyField(maximumAlpha);

        serializedObject.ApplyModifiedProperties();
    }
Exemplo n.º 24
0
 /// <summary>
 /// Draw the standard read-only Script property.
 /// </summary>
 protected virtual void DrawScript()
 {
     EditorGUI.BeginDisabledGroup(true);
     EditorGUILayout.ObjectField(EditorGUIUtility.TrTempContent("Script"), MonoScript.FromMonoBehaviour((MonoBehaviour)target), typeof(MonoBehaviour), false);
     EditorGUI.EndDisabledGroup();
 }
Exemplo n.º 25
0
        private void OnEnable()
        {
            Utils.editorPath = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this)));

            SceneView.onSceneGUIDelegate += OnSceneGUI;
            EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyWindowItemOnGUI;
        }
        public override void OnInspectorGUI()
        {
            GUI.enabled = false;
            EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour((XRDirectInteractor)target), typeof(XRDirectInteractor), false);
            GUI.enabled = true;

            serializedObject.Update();

            EditorGUILayout.PropertyField(m_InteractionManager, Tooltips.interactionManager);
            EditorGUILayout.PropertyField(m_InteractionLayerMask, Tooltips.interactionLayerMask);
            EditorGUILayout.PropertyField(m_AttachTransform, Tooltips.attachTransform);
            EditorGUILayout.PropertyField(m_StartingSelectedInteractable, Tooltips.startingSelectedInteractable);
            EditorGUILayout.PropertyField(m_SelectActionTrigger, Tooltips.selectActionTrigger);
            if (m_StartingSelectedInteractable.objectReferenceValue != null &&
                (m_SelectActionTrigger.enumValueIndex == 2 || m_SelectActionTrigger.enumValueIndex == 3))
            {
                EditorGUILayout.HelpBox(Tooltips.startingInteractableWarning, MessageType.Warning, true);
            }
            EditorGUILayout.PropertyField(m_HideControllerOnSelect, Tooltips.hideControllerOnSelect);

            EditorGUILayout.Space();

            m_ShowSoundEvents = EditorGUILayout.Foldout(m_ShowSoundEvents, "Sound Events");
            if (m_ShowSoundEvents)
            {
                EditorGUILayout.PropertyField(m_PlayAudioClipOnSelectEnter, Tooltips.PlayAudioClipOnSelectEnter);
                if (m_PlayAudioClipOnSelectEnter.boolValue)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(m_AudioClipForOnSelectEnter, Tooltips.AudioClipForOnSelectEnter);
                    EditorGUI.indentLevel--;
                }

                EditorGUILayout.PropertyField(m_PlayAudioClipOnSelectExit, Tooltips.PlayAudioClipOnSelectExit);
                if (m_PlayAudioClipOnSelectExit.boolValue)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(m_AudioClipForOnSelectExit, Tooltips.AudioClipForOnSelectExit);
                    EditorGUI.indentLevel--;
                }

                EditorGUILayout.PropertyField(m_PlayAudioClipOnHoverEnter, Tooltips.PlayAudioClipOnHoverEnter);
                if (m_PlayAudioClipOnHoverEnter.boolValue)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(m_AudioClipForOnHoverEnter, Tooltips.AudioClipForOnHoverEnter);
                    EditorGUI.indentLevel--;
                }

                EditorGUILayout.PropertyField(m_PlayAudioClipOnHoverExit, Tooltips.PlayAudioClipOnHoverExit);
                if (m_PlayAudioClipOnHoverExit.boolValue)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(m_AudioClipForOnHoverExit, Tooltips.AudioClipForOnHoverExit);
                    EditorGUI.indentLevel--;
                }
            }

            EditorGUILayout.Space();

            m_ShowHapticEvents = EditorGUILayout.Foldout(m_ShowHapticEvents, "Haptic Events");
            if (m_ShowHapticEvents)
            {
                EditorGUILayout.PropertyField(m_PlayHapticsOnSelectEnter, Tooltips.playHapticsOnSelectEnter);
                if (m_PlayHapticsOnSelectEnter.boolValue)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(m_HapticSelectEnterIntensity, Tooltips.hapticSelectEnterIntensity);
                    EditorGUILayout.PropertyField(m_HapticSelectEnterDuration, Tooltips.hapticSelectEnterDuration);
                    EditorGUI.indentLevel--;
                }

                EditorGUILayout.PropertyField(m_PlayHapticsOnSelectExit, Tooltips.playHapticsOnSelectExit);
                if (m_PlayHapticsOnSelectExit.boolValue)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(m_HapticSelectExitIntensity, Tooltips.hapticSelectExitIntensity);
                    EditorGUILayout.PropertyField(m_HapticSelectExitDuration, Tooltips.hapticSelectExitDuration);
                    EditorGUI.indentLevel--;
                }

                EditorGUILayout.PropertyField(m_PlayHapticsOnHoverEnter, Tooltips.playHapticsOnHoverEnter);
                if (m_PlayHapticsOnHoverEnter.boolValue)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(m_HapticHoverEnterIntensity, Tooltips.hapticHoverEnterIntensity);
                    EditorGUILayout.PropertyField(m_HapticHoverEnterDuration, Tooltips.hapticHoverEnterDuration);
                    EditorGUI.indentLevel--;
                }

                EditorGUILayout.PropertyField(m_PlayHapticsOnHoverExit, Tooltips.playHapticsOnHoverExit);
                if (m_PlayHapticsOnHoverExit.boolValue)
                {
                    EditorGUI.indentLevel++;
                    EditorGUILayout.PropertyField(m_HapticHoverExitIntensity, Tooltips.hapticHoverExitIntensity);
                    EditorGUILayout.PropertyField(m_HapticHoverExitDuration, Tooltips.hapticHoverExitDuration);
                    EditorGUI.indentLevel--;
                }
            }

            EditorGUILayout.Space();

            m_ShowInteractorEvents = EditorGUILayout.Toggle("Show Interactor Events", m_ShowInteractorEvents);
            if (m_ShowInteractorEvents)
            {
                // UnityEvents have not yet supported Tooltips
                EditorGUILayout.PropertyField(m_OnHoverEnter);
                EditorGUILayout.PropertyField(m_OnHoverExit);
                EditorGUILayout.PropertyField(m_OnSelectEnter);
                EditorGUILayout.PropertyField(m_OnSelectExit);
            }

            serializedObject.ApplyModifiedProperties();
        }
Exemplo n.º 27
0
        private void DrawGeneratorSetting(
            GeneratorEntry entry,
            NodeGUI node,
            AssetReferenceStreamManager streamManager,
            NodeGUIEditor editor,
            Action onValueChanged)
        {
            var generator = entry.m_instance.Get <IAssetGenerator>(editor.CurrentEditingGroup);

            using (new EditorGUILayout.VerticalScope(GUI.skin.box)) {
                using (new GUILayout.HorizontalScope())
                {
                    var newName = EditorGUILayout.TextField("Name", entry.m_name);
                    if (newName != entry.m_name)
                    {
                        using (new RecordUndoScope("Change Name", node, true)) {
                            entry.m_name = newName;
                            UpdateGeneratorEntry(node, entry);
                            onValueChanged();
                        }
                    }

                    if (GUILayout.Button(m_popupIcon, GUI.skin.label, GUILayout.Width(20f)))
                    {
                        var menu = new GenericMenu();
                        menu.AddItem(new GUIContent("Remove Generator"), false, () =>
                        {
                            m_removingEntry = entry;
                        });
                        menu.ShowAsContext();
                    }
                }

                var map = AssetGeneratorUtility.GetAttributeAssemblyQualifiedNameMap();
                if (map.Count > 0)
                {
                    using (new GUILayout.HorizontalScope()) {
                        GUILayout.Label("AssetGenerator");
                        var guiName = AssetGeneratorUtility.GetGUIName(entry.m_instance.ClassName);

                        if (GUILayout.Button(guiName, "Popup", GUILayout.MinWidth(150f)))
                        {
                            var builders = map.Keys.ToList();

                            if (builders.Count > 0)
                            {
                                NodeGUI.ShowTypeNamesMenu(guiName, builders, (string selectedGUIName) =>
                                {
                                    using (new RecordUndoScope("Change AssetGenerator class", node, true)) {
                                        generator = AssetGeneratorUtility.CreateGenerator(selectedGUIName);
                                        entry.m_instance.Set(editor.CurrentEditingGroup, generator);
                                        onValueChanged();
                                    }
                                }
                                                          );
                            }
                        }

                        MonoScript s = TypeUtility.LoadMonoScript(entry.m_instance.ClassName);

                        using (new EditorGUI.DisabledScope(s == null)) {
                            if (GUILayout.Button("Edit", GUILayout.Width(50)))
                            {
                                AssetDatabase.OpenAsset(s, 0);
                            }
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(entry.m_instance.ClassName))
                    {
                        EditorGUILayout.HelpBox(
                            string.Format(
                                "Your AssetGenerator script {0} is missing from assembly. Did you delete script?", entry.m_instance.ClassName), MessageType.Info);
                    }
                    else
                    {
                        string[] menuNames = Model.Settings.GUI_TEXT_MENU_GENERATE_ASSETGENERATOR.Split('/');
                        EditorGUILayout.HelpBox(
                            string.Format(
                                "You need to create at least one AssetGenerator script to use this node. To start, select {0}>{1}>{2} menu and create new script from template.",
                                menuNames[1], menuNames[2], menuNames[3]
                                ), MessageType.Info);
                    }
                }

                GUILayout.Space(10f);

                editor.DrawPlatformSelector(node);
                using (new EditorGUILayout.VerticalScope()) {
                    var disabledScope = editor.DrawOverrideTargetToggle(node, entry.m_instance.ContainsValueOf(editor.CurrentEditingGroup), (bool enabled) => {
                        if (enabled)
                        {
                            entry.m_instance.CopyDefaultValueTo(editor.CurrentEditingGroup);
                        }
                        else
                        {
                            entry.m_instance.Remove(editor.CurrentEditingGroup);
                        }
                        onValueChanged();
                    });

                    using (disabledScope) {
                        if (generator != null)
                        {
                            Action onChangedAction = () => {
                                using (new RecordUndoScope("Change AssetGenerator Setting", node)) {
                                    entry.m_instance.Set(editor.CurrentEditingGroup, generator);
                                    onValueChanged();
                                }
                            };

                            generator.OnInspectorGUI(onChangedAction);
                        }
                    }
                }
            }
        }
Exemplo n.º 28
0
 protected void RestoreMonoScriptAssembly(MonoScript script)
 {
     ChangeMonoScriptAssembly(script, "Assembly-CSharp");
 }
Exemplo n.º 29
0
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);
        if (property.objectReferenceValue != null)
        {
            property.isExpanded = EditorGUI.Foldout(new Rect(position.x, position.y, EditorGUIUtility.labelWidth, EditorGUIUtility.singleLineHeight), property.isExpanded, property.displayName, true);
            EditorGUI.PropertyField(new Rect(EditorGUIUtility.labelWidth + 14, position.y, position.width - EditorGUIUtility.labelWidth, EditorGUIUtility.singleLineHeight), property, GUIContent.none, true);
            if (GUI.changed)
            {
                property.serializedObject.ApplyModifiedProperties();
            }
            if (property.objectReferenceValue == null)
            {
                EditorGUIUtility.ExitGUI();
            }

            if (property.isExpanded)
            {
                // Draw a background that shows us clearly which fields are part of the ScriptableObject
                GUI.Box(new Rect(0, position.y + EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing - 1, Screen.width, position.height - EditorGUIUtility.singleLineHeight - EditorGUIUtility.standardVerticalSpacing), "");

                EditorGUI.indentLevel++;
                var data = (ScriptableObject)property.objectReferenceValue;
                SerializedObject serializedObject = new SerializedObject(data);

                // Iterate over all the values and draw them
                SerializedProperty prop = serializedObject.GetIterator();
                float y = position.y + EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
                if (prop.NextVisible(true))
                {
                    do
                    {
                        // Don't bother drawing the class file
                        if (prop.name == "m_Script")
                        {
                            continue;
                        }
                        float height = EditorGUI.GetPropertyHeight(prop, new GUIContent(prop.displayName), true);
                        EditorGUI.PropertyField(new Rect(position.x, y, position.width, height), prop, true);
                        y += height + EditorGUIUtility.standardVerticalSpacing;
                    }while (prop.NextVisible(false));
                }
                if (GUI.changed)
                {
                    serializedObject.ApplyModifiedProperties();
                }

                EditorGUI.indentLevel--;
            }
        }
        else
        {
            EditorGUI.ObjectField(new Rect(position.x, position.y, position.width - 60, EditorGUIUtility.singleLineHeight), property);
            if (GUI.Button(new Rect(position.x + position.width - 58, position.y, 58, EditorGUIUtility.singleLineHeight), "Create"))
            {
                string selectedAssetPath = "Assets";
                if (property.serializedObject.targetObject is MonoBehaviour)
                {
                    MonoScript ms = MonoScript.FromMonoBehaviour((MonoBehaviour)property.serializedObject.targetObject);
                    selectedAssetPath = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(ms));
                }
                Type type = fieldInfo.FieldType;
                if (type.IsArray)
                {
                    type = type.GetElementType();
                }
                else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>))
                {
                    type = type.GetGenericArguments()[0];
                }
                property.objectReferenceValue = CreateAssetWithSavePrompt(type, selectedAssetPath);
            }
        }
        property.serializedObject.ApplyModifiedProperties();
        EditorGUI.EndProperty();
    }
        /// <inheritdoc />
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (property.objectReferenceValue != null)
            {
                using (var serializedObject = new SerializedObject(property.objectReferenceValue))
                {
                    // First, render a header for the TileLayer.

                    if (serializedObject == null)
                    {
                        EditorGUI.LabelField(position, property.objectReferenceValue.GetType().Name);
                        return;
                    }

                    var tileLayer = (TileLayer)property.GetValue();
                    if (tileLayer == null)
                    {
                        return;
                    }

                    var script = MonoScript.FromMonoBehaviour(tileLayer);

                    var tileLayerNamePosition = position;
                    EditorGUILayout.BeginHorizontal();
                    {
                        Undo.RecordObject(serializedObject.targetObject, "Enabled");
                        var iconPosition = position;
                        iconPosition.height = EditorGUIUtility.singleLineHeight;
                        iconPosition.width  = iconPosition.height;
                        GUI.Box(iconPosition, AssetPreview.GetMiniThumbnail(script), GUIStyle.none);

                        var togglePosition = iconPosition;
                        togglePosition.x    += 4 + EditorStyles.toggle.padding.left;
                        togglePosition.width = EditorStyles.toggle.padding.left;
                        var customToggleStyle = new GUIStyle(EditorStyles.toggle)
                        {
                            alignment = TextAnchor.MiddleCenter
                        };
                        tileLayer.enabled = EditorGUI.Toggle(togglePosition, tileLayer.enabled, customToggleStyle);
                        serializedObject.Update();

                        var name      = ObjectNames.NicifyVariableName(script.name) + " (Script)";
                        var labelSize = EditorStyles.boldLabel.CalcSize(new GUIContent(name));
                        tileLayerNamePosition.height = EditorGUIUtility.singleLineHeight;
                        tileLayerNamePosition.x     += 4 + EditorStyles.toggle.padding.left;
                        tileLayerNamePosition.width  = labelSize.x + EditorStyles.toggle.padding.left;
                        EditorGUI.LabelField(tileLayerNamePosition, new GUIContent(name), EditorStyles.boldLabel);
                    }
                    EditorGUILayout.EndHorizontal();

                    var fieldRect = new Rect(position)
                    {
                        height = EditorGUIUtility.singleLineHeight
                    };
                    var propertyRects = new List <Rect>();
                    fieldRect.xMin += 5;
                    var marchingRect = new Rect(fieldRect);
                    marchingRect.y += marchingRect.height + EditorGUIUtility.standardVerticalSpacing;

                    // For the content of the TileLayer, either automatically generate UI for the fields,
                    // or defer to the CustomTileLayerDrawer.

                    EditorGUI.indentLevel++;

                    if (_propertyDrawerCache.Value.TryGetValue(property.objectReferenceValue.GetType(), out var propertyDrawer))
                    {
                        // Property has a drawer... use that to display.
                        propertyDrawer.OnGUI(marchingRect, property, label);
                    }
                    else
                    {
                        // Property does not have a drawer, use a draw that shows all the serialized fields.
                        var field = serializedObject.GetIterator();
                        field.NextVisible(true);

                        while (field.NextVisible(false))
                        {
                            marchingRect.height = EditorGUI.GetPropertyHeight(field, true);
                            propertyRects.Add(marchingRect);
                            marchingRect.y += marchingRect.height + EditorGUIUtility.standardVerticalSpacing;
                        }

                        int index = 0;
                        field = serializedObject.GetIterator();
                        field.NextVisible(true);

                        //Replacement for "editor.OnInspectorGUI ();" so we have more control on how we draw the editor
                        while (field.NextVisible(false))
                        {
                            try
                            {
                                EditorGUI.PropertyField(propertyRects[index], field, true);
                            }
                            catch (StackOverflowException)
                            {
                                field.objectReferenceValue = null;
                                Debug.LogError(
                                    "Detected self-nesting causing a StackOverflowException, avoid using the same object inside a nested structure.");
                            }

                            ++index;
                        }
                    }

                    serializedObject.ApplyModifiedProperties();

                    EditorGUI.indentLevel--;

                    // Shows context menu for editing the associated script, i.e. will open text editor like Visual Studio.
                    var currentEvent = Event.current;
                    if (currentEvent.type == EventType.ContextClick)
                    {
                        if (tileLayerNamePosition.Contains(currentEvent.mousePosition))
                        {
                            if (script != null)
                            {
                                GenericMenu menu = new GenericMenu();
                                menu.AddItem(new GUIContent("Edit Script"), false, () => AssetDatabase.OpenAsset(script));
                                menu.ShowAsContext();
                            }
                        }
                    }
                }
            }
            else
            {
                EditorGUI.LabelField(position, "Unknown");
            }
        }