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

SearchService.Request

Declaration

public static Search.ISearchList Request(string searchText, Search.SearchFlags options);
public static Search.ISearchList Request(Search.SearchContext context, Search.SearchFlags options);

Параметры

Параметр Описание
searchText Запрос поиска для выполнения.
контекст Контекст поиска, используемый для отслеживания асинхронных запросов. Вы должны удалить этот контекст самостоятельно.
варианты Параметры, определяющие, как выполняется запрос.

Возвращаемое значение

ISearchList Асинхронный список элементов поиска.

Описание

Выполняет запрос поиска, который асинхронно получает результаты поиска.

В следующем примере выполняется запрос и печатаются результаты по многим кадрам с использованием EditorApplication.update.

[MenuItem("Examples/SearchService/Request List")]
public static void RequestList()
{
    ISearchList results = SearchService.Request("*.cs");

    // It is important to note that when you request some search results,
    // that you need to enumerate them asynchronously using the returned search list.
    AsyncResultEnumerator.Fetch(results, item => Debug.Log(item));
}

class AsyncResultEnumerator
{
    private Action<SearchItem> m_OnEnumerate;
    private IEnumerator<SearchItem> m_Iterator;

    public static AsyncResultEnumerator Fetch(ISearchList results, Action<SearchItem> onEnumerate)
    {
        return new AsyncResultEnumerator(results, onEnumerate);
    }

    public AsyncResultEnumerator(ISearchList results, Action<SearchItem> onEnumerate)
    {
        m_OnEnumerate = onEnumerate;
        m_Iterator = results.GetEnumerator();
        EditorApplication.update += EnumerateResults;
    }

    private void EnumerateResults()
    {
        if (m_Iterator == null || !m_Iterator.MoveNext())
        {
            m_Iterator = null;
            EditorApplication.update -= EnumerateResults;
        }
        else if (m_Iterator.Current != null)
            m_OnEnumerate(m_Iterator.Current);
    }
}

Если вы запускаете сопутствующую программу, вы можете получить результаты, похожие на следующие:

public static IEnumerable<SearchItem> YieldResults()
{
    ISearchList results = SearchService.Request("*.cs");
    foreach (var result in results)
        yield return result;
}

Declaration

public static void Request(string searchText, Action<SearchContext,IList<SearchItem>> onSearchCompleted, Search.SearchFlags options);
public static void Request(Search.SearchContext context, Action<SearchContext,IList<SearchItem>> onSearchCompleted, Search.SearchFlags options);

Параметры

Параметр Описание
onSearchCompleted Обратный вызов вызван, когда запрос поиска завершен и доступны все результаты.

Описание

Выполняет запрос поиска и вызывает указанную функцию, когда доступны все результаты.

[MenuItem("Examples/SearchService/Request All")]
public static void RequestAll()
{
    SearchService.Request("t:texture", (SearchContext context, IList<SearchItem> items) =>
    {
        Debug.Log("All Textures");
        foreach (var item in items)
            Debug.Log(item);
    }, SearchFlags.Debug);
}

Declaration

public static void Request(string searchText, Action<SearchContext,IEnumerable<SearchItem>> onIncomingItems, Action<SearchContext> onSearchCompleted, Search.SearchFlags options);
public static void Request(Search.SearchContext context, Action<SearchContext,IEnumerable<SearchItem>> onIncomingItems, Action<SearchContext> onSearchCompleted, Search.SearchFlags options);

Параметры

Параметр Описание
onIncomingItems Обратный вызов вызывается каждый раз, когда найдена и доступна партия результатов.
onSearchCompleted Обратный вызов, вызываемый при завершении запроса поиска.

Описание

Выполняет запрос поиска и обратный вызов для каждой пакета входящих результатов. Возможно, что вы получите дубликаты элементов, поэтому фильтруйте окончательный список, если это необходимо.

[MenuItem("Examples/SearchService/Request Async")]
public static void RequestAsync()
{
    var batchCount = 0;
    var totalItemCount = 0;

    void OnIncomingResults(SearchContext context, IEnumerable<SearchItem> items)
    {
        var batchItemCount = items.Count();
        totalItemCount += batchItemCount;
        Debug.Log($"#{++batchCount} Incoming materials ({batchItemCount}): {string.Join("\n", items)}");
    }

    void OnSearchCompleted(SearchContext context)
    {
        Debug.Log($"Query <b>\"{context.searchText}\"</b> completed with a total of {totalItemCount}");
    }

    SearchService.Request("t:material", OnIncomingResults, OnSearchCompleted, SearchFlags.Debug);
}