Unity 6.3
0 онлайн 77 гостей 3 в системе
Вход

EditorGUIUtility.ShowObjectPicker

Declaration

public static void ShowObjectPicker(Object obj, bool allowSceneObjects, string searchFilter, int controlID);

Параметры

Параметр Описание
Объект Объект, выбираемый по умолчанию.
allowSceneObjects Разрешается ли выбор объектов Scene, или должен показываться только ассет.
searchFilter Применимый по умолчанию фильтр поиска. Это текст первоначального запроса поиска, который применяется при открытии инструмента выбора объекта.
controlID Идентификатор контроля для установки. Это полезно, если вы показываете более одного из этих. Вы можете получить значение позже.

Описание

Показать выборщик объектов из кода.

<T>: Тип объектов, которые доступны для выбора в выборщике объектов.

Как только пользователь взаимодействует с выборщиком объектов, он отвечает, отправляя события ExecuteCommand обратно в OnGUI, который вызвал эту функцию. Сообщения:

  • ObjectSelectorUpdated: Выбранный объект был изменён. Вызов GetObjectPickerObject для чтения выбранного объекта.
  • ObjectSelectorClosed: Пользователь закрыл выборщик объектов.
  • ObjectSelectorCanceled: Пользователь отменил операцию подбора и подбранный объект был закрыт.

Вот пример того, как она может быть вызвана для любого контроля во время вызова OnGUI:

static void CallShowPicker<T>(UnityEngine.Object currentObjectValue, int currentControlId) where T : UnityEngine.Object
{
    // Show an object picker with the `currentObjectValue` selected. We pass true to allow
    // scene objects. We set the initial search query string to an empty string. The `currentControlId`
    // is passed to us during the OnGUI call, for any object field or other control that needs to show the object picker.
    EditorGUIUtility.ShowObjectPicker<T>(currentObjectValue, true, "", currentControlId);
}

Вот как поле объекта, использующее предыдущий метод, может быть настроено во время вызова OnGUI:

public static void DoObjectField(Rect position, SerializedProperty property, Type objType, GUIContent label)
{
    label = EditorGUI.BeginProperty(position, label, property);
    // Generate a controlId for this object field. Use a unique hint integer for correct matching of controls.
    var controlId = GUIUtility.GetControlID("Example_EditorGUIUtility_ShowObjectPicker".GetHashCode(), FocusType.Keyboard, position);
    position = EditorGUI.PrefixLabel(position, controlId, label);
    DoObjectField(position, position, controlId, objType, property);
    EditorGUI.EndProperty();
}

Наконец, вот как можно обрабатывать события ExecuteCommand во время вызова OnGUI:

static bool HandleCommands(SerializedProperty property, ref UnityEngine.Object currentObjectValue, UnityEngine.Object originalObjectValue, Type objectType, int currentControlId)
{
    var evt = Event.current;
    switch (evt.type)
    {
        case EventType.ExecuteCommand:
            string commandName = evt.commandName;
            if (commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == currentControlId)
            {
                currentObjectValue = AssignSelectedObject(EditorGUIUtility.GetObjectPickerObject(), property, objectType, evt);
                return true;
            }
            if (commandName == "ObjectSelectorClosed" && EditorGUIUtility.GetObjectPickerControlID() == currentControlId)
            {
                return true;
            }
            if (commandName == "ObjectSelectorCanceled" && EditorGUIUtility.GetObjectPickerControlID() == currentControlId)
            {
                if (property != null)
                    property.objectReferenceValue = originalObjectValue;
                else
                    currentObjectValue = originalObjectValue;
                return true;
            }
            break;
        default:
            return false;
    }

    return false;
}