using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Search;
using UnityEngine;
static class SearchProvider_priority
{
static string typeColors = "example_colors_priority";
static string displayNameColors = "example_Colors_priority";
static string typeFruits = "example_fruits_priority";
static string displayNameFruits = "example_Fruits_priority";
static List<string> colors = new List<string> { "orange", "red", "green", "blue" };
static List<string> fruits = new List<string> { "orange", "apple", "banana", "strawberry" };
[SearchItemProvider]
internal static SearchProvider CreateProviderColors()
{
return new SearchProvider(typeColors, displayNameColors)
{
priority = 99991,
filterId = "c:",
isExplicitProvider = false,
fetchItems = FetchColors
};
}
static IEnumerable<SearchItem> FetchColors(SearchContext context, List<SearchItem> items, SearchProvider provider)
{
var expression = context.searchQuery;
if (colors.Contains(expression))
{
var id = expression + "(color)";
yield return provider.CreateItem(context, id, id, id, null, null);
}
}
[SearchItemProvider]
internal static SearchProvider CreateProviderFruits()
{
return new SearchProvider(typeFruits, displayNameFruits)
{
priority = 99992,
filterId = "f:",
isExplicitProvider = false,
fetchItems = FetchFruits
};
}
static IEnumerable<SearchItem> FetchFruits(SearchContext context, List<SearchItem> items, SearchProvider provider)
{
var expression = context.searchQuery;
if (fruits.Contains(expression))
{
var id = expression + "(fruit)";
yield return provider.CreateItem(context, id, id, id, null, null);
}
}
[MenuItem("Examples/SearchProvider/priority")]
public static void Run()
{
using (var context = SearchService.CreateContext(new []{typeColors, typeFruits}, "orange"))
{
// For the purpose if this example, we use the flag synchronous to get the items immediately.
var results = SearchService.Request(context, SearchFlags.Synchronous);
// Results are not sorted, sort them by score first then provider priority.
// Color should be the first one (both items have the same score but color provider has the lowest priority).
var sortedResults = new List<SearchItem>(results);
sortedResults.Sort((itemA, itemB) =>
{
// Sort by score first (lower is better).
var scoreDiff = itemA.score - itemB.score;
if (scoreDiff != 0)
return scoreDiff;
// If same score, sort by provider priority (lower is better).
return itemA.provider.priority - itemB.provider.priority;
});
Debug.Log(sortedResults.Count);
Debug.Log(sortedResults[0].description); // "orange(color)";
Debug.Log(sortedResults[1].description); // "orange(fruit)";
}
}
}