0

Начал разбираться с кастомным интерфейсом свойств инспектора, так как стандартный перестал устраивать и написал свой кастомный PropertyDrawer, всё хорошо до первого Play, после нажатия на него ловлю ошибку:

ArgumentException: Getting control 1's position in a group with only 1 controls when doing repaint
Aborting
UnityEngine.GUILayoutGroup.GetNext () (at <9ff04fda545c4aacb8dab659ad40b2f4>:0)
UnityEngine.GUILayoutUtility.BeginLayoutGroup (UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options, System.Type layoutType) (at <9ff04fda545c4aacb8dab659ad40b2f4>:0)
UnityEditor.EditorGUILayout.BeginHorizontal (UnityEngine.GUIContent content, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) (at <4f969f18b6984883abf0f762caf9325d>:0)
UnityEditor.EditorGUILayout.BeginHorizontal (UnityEngine.GUILayoutOption[] options) (at <4f969f18b6984883abf0f762caf9325d>:0)
Source.HealthDrawer.OnGUI (UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) (at Assets/Editor/HealthDrawer.cs:16)
UnityEditor.PropertyDrawer.OnGUISafe (UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) (at <4f969f18b6984883abf0f762caf9325d>:0)
UnityEditor.PropertyHandler.OnGUI (UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, System.Boolean includeChildren, UnityEngine.Rect visibleArea) (at <4f969f18b6984883abf0f762caf9325d>:0)
UnityEditor.GenericInspector.OnOptimizedInspectorGUI (UnityEngine.Rect contentRect) (at <4f969f18b6984883abf0f762caf9325d>:0)
UnityEditor.UIElements.InspectorElement+<>c__DisplayClass59_0.<CreateIMGUIInspectorFromEditor>b__0 () (at <a122028f8c314654ad750c3d9eb1f725>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

И пропадает мой кастомный PropertyDrawer с инспектора и не появляется до тех пор, пока не сохраню класс с пустым OnGUI и заново не вставлю код с моим OnGUI

HealthDrawer.cs

#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;

namespace Source
{
    [CustomPropertyDrawer(typeof(Health))]
    public class HealthDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            SerializedProperty currentHealth = property.FindPropertyRelative("m_currentHealth");
            SerializedProperty maxHealth = property.FindPropertyRelative("m_maxHealth");
            SerializedProperty minHealth = property.FindPropertyRelative("m_minHealth");

            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.PrefixLabel(label);
                GUILayout.Label("Current: ");
                currentHealth.floatValue = EditorGUILayout.Slider(currentHealth.floatValue, minHealth.floatValue, maxHealth.floatValue);
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.PrefixLabel(" ");
                GUILayout.Label("Min: ");
                minHealth.floatValue = EditorGUILayout.FloatField(minHealth.floatValue);
                GUILayout.Label("Max: ");
                maxHealth.floatValue = EditorGUILayout.FloatField(maxHealth.floatValue);
                currentHealth.floatValue = Mathf.Clamp(currentHealth.floatValue, minHealth.floatValue, maxHealth.floatValue);
            }
            EditorGUILayout.EndHorizontal();
        }
    }
}
#endif
1
  • #if UNITY_EDITOR и #endif быть не должно. Скрипты для редактора должны находиться в папке с именем Editor и их контент не попадает в билд. Таких папок может быть много, не одна.
    – Yaroslav
    24 апр 2021 в 21:11

1 ответ 1

0

Работоспособность этого кода хоть в каком-то виде - случайность. PropertyDrawer не поддерживает GUILayout методы.

Note that for performance reasons, EditorGUILayout functions are not usable with PropertyDrawers.

Старая IMGUI система признана устаревшей, на ее смену пришла UIElements, которая все еще находится в раннем доступе, но, когда-нибудь ее релизнут.


Если очень хочется сделать через PropertyDrawer: на этапе отрисовки в ваш метод передается прямоугольник Rect position, в рамках которого вы и должны рисовать.

4
  • Какие люди! А как же токсичное сообщество? Я тут тружусь на очередной бан в поте лица.
    – Yaroslav
    24 апр 2021 в 21:36
  • @Yaroslav я не буду ничего обсуждать, аккаунт восстановлен для англоязычного SO. 24 апр 2021 в 22:22
  • Так он ещё таксичней, там 90% вопросов с тегом unity3d заминусованные. 😆 Хотя задающие вопросы в 100 раз приветливее и культурнее русских.
    – Yaroslav
    24 апр 2021 в 22:35
  • @Yaroslav я не ради unity туда иду ;) 24 апр 2021 в 22:51

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.