搜索提供程序使用 fetchItems 函数来搜索项目并过滤结果。fetchItems 函数具有以下特征签名:
// context: the necessary search context (for example, tokenized search and
// sub-filters).
// items: list of items to populate (if not using the asynchronous api)
// provider: the Search Provider itself
public delegate IEnumerable<SearchItem> GetItemsHandler(SearchContext context,
List<SearchItem> items,
SearchProvider provider);
SearchProvider 必须将新的 SearchItem 添加到 items 列表,否则会返回 IEnumerable<SearchItem>。
注意:如果不使用异步
fetchItemsAPI,则必须在fetchItems函数中返回null。
SearchItem 是一种简单的结构:
public struct SearchItem
{
public readonly string id;
// The item score affects how Search sorts the item within the results from the Search Provider.
public int score;
// Optional: Display name of the item. If the item does not have one,
// SearchProvider.fetchLabel is called).
public string label;
// If the item does not have a description SearchProvider.fetchDescription
// is called when Search first displays the item.
public string description;
// If true, the description already has rich text formatting.
public SearchItemDescriptionFormat descriptionFormat;
// If the item does not have a thumbnail, SearchProvider.fetchThumbnail
// is called when Search first displays the item.
public Texture2D thumbnail;
// Search Provider user-customizable content
public object data;
}
SearchItem 只需要 id。
提示:根据
SearchContext.searchText进行过滤时,请使用进行部分搜索的静态函数SearchProvider.MatchSearchGroup。
要对项使用模糊搜索,可以使用 FuzzySearch.FuzzyMatch,如下面的示例所示:
if (FuzzySearch.FuzzyMatch(sq, CleanString(item.label), ref score, matches))
item.label = RichTextFormatter.FormatSuggestionTitle(item.label, matches);
所有搜索项都根据同一提供程序及其 score 的项进行排序。较低分数显示在项列表顶部(升序排序)。
当搜索提供程序需要很长时间来计算其结果或依赖于 WebRequest 等异步搜索引擎时,可以使用异步 fetchItems API。
要使用异步 API,请让 fetchItems 函数返回 IEnumerable<SearchItem>。IEnumerable<SearchItem> 应该是一个产生结果的函数,以便 API 可以一次获取一项。
返回 IEnumerable<SearchItem> 时,枚举器将在应用程序更新期间存储和迭代。枚举在多个应用程序更新期间继续,直到完成。
迭代时间受约束,以确保__ UI__(即用户界面,User Interface)让用户能够与您的应用程序进行交互。Unity 目前支持三种 UI 系统。更多信息
See in Glossary 不被阻止。但是,由于调用位于主线程中,因此如果结果尚未准备就绪,应确保尽快生成。
下面的示例演示了如何使用异步 fetchItems API:
public class AsyncSearchProvider : SearchProvider
{
public AsyncSearchProvider(string id, string displayName = null)
: base(id, displayName)
{
fetchItems = (context, items, provider) => FetchItems(context, provider);
}
private IEnumerable<SearchItem> FetchItems(SearchContext context, SearchProvider provider)
{
while(ResultsNotReady())
{
yield return null;
}
var oneItem = // Get an item
yield return oneItem;
var anotherItem = // Get another item
yield return anotherItem;
if(SomeConditionThatBreaksTheSearch())
{
// Search must be terminated
yield break;
}
// You can iterate over an enumerable. The enumeration
// continues where it left.
foreach(var item in someItems)
{
yield return item;
}
}
}
AssetStoreProvider.cs:使用 WebRequest 查询资源商店。ESS.cs:创建一个启动 Entrian Source Search 索引器的进程,该索引器为项目中的资源提供全文搜索。