class in UnityEditor.Search
Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.
CloseFor some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.
CloseProvides various utility functions that are used by SearchProvider.
using System; using System.Collections; using System.Globalization; using System.Linq; using UnityEditor.Search; using UnityEditor; using UnityEngine; /// <summary> /// Custom provider showing how to implement a custom Query Engine supporting a Spatial search filter. /// </summary> public static class SpatialProvider { internal static string type = "spl"; internal static string displayName = "Spatial"; static GameObject[] s_GameObjects; static QueryEngine<GameObject> s_QueryEngine; [SearchItemProvider] internal static SearchProvider CreateProvider() { return new SearchProvider(type, displayName) { active = false, filterId = "spl:", onEnable = OnEnable, fetchItems = (context, items, provider) => SearchItems(context, provider), fetchLabel = FetchLabel, fetchDescription = FetchDescription, fetchThumbnail = FetchThumbnail, fetchPreview = FetchPreview, trackSelection = TrackSelection, isExplicitProvider = false, }; } static void OnEnable() { s_GameObjects = SearchUtils.FetchGameObjects().ToArray(); s_QueryEngine = new QueryEngine<GameObject>(); // Id supports all operators s_QueryEngine.AddFilter("id", go => go.GetInstanceID()); // Name supports only :, = and != s_QueryEngine.AddFilter("n", go => go.name, new[] {":", "=", "!="}); // Add distance filtering. Does not support :. s_QueryEngine.AddFilter("dist", DistanceHandler, DistanceParamHandler, new[] {"=", "!=", "<", ">", "<=", ">="}); } static IEnumerator SearchItems(SearchContext context, SearchProvider provider) { var query = s_QueryEngine.ParseQuery(context.searchQuery); if (!query.valid) yield break; var filteredObjects = query.Apply(s_GameObjects); foreach (var filteredObject in filteredObjects) { yield return provider.CreateItem(filteredObject.GetInstanceID().ToString(), null, null, null, filteredObject.GetInstanceID()); } } static string FetchLabel(SearchItem item, SearchContext context) { if (item.label != null) return item.label; var go = ObjectFromItem(item); if (!go) return item.id; var transformPath = SearchUtils.GetTransformPath(go.transform); var components = go.GetComponents<Component>(); if (components.Length > 2 && components[1] && components[components.Length - 1]) item.label = $"{transformPath} ({components[1].GetType().Name}..{components[components.Length - 1].GetType().Name})"; else if (components.Length > 1 && components[1]) item.label = $"{transformPath} ({components[1].GetType().Name})"; else item.label = $"{transformPath} ({item.id})"; return item.label; } static string FetchDescription(SearchItem item, SearchContext context) { var go = ObjectFromItem(item); return (item.description = SearchUtils.GetHierarchyPath(go)); } static Texture2D FetchThumbnail(SearchItem item, SearchContext context) { var obj = ObjectFromItem(item); if (obj == null) return null; return item.thumbnail = GetThumbnailForGameObject(obj); } static Texture2D FetchPreview(SearchItem item, SearchContext context, Vector2 size, FetchPreviewOptions options) { var obj = ObjectFromItem(item); if (obj == null) return item.thumbnail; var assetPath = SearchUtils.GetHierarchyAssetPath(obj, true); if (string.IsNullOrEmpty(assetPath)) return item.thumbnail; if (options.HasFlag(FetchPreviewOptions.Large)) { if (AssetPreview.GetAssetPreview(obj) is Texture2D tex) return tex; } return GetAssetPreviewFromPath(assetPath, size, options); } static void TrackSelection(SearchItem item, SearchContext context) { var obj = ObjectFromItem(item); if (obj) Selection.activeGameObject = obj; if (SceneView.lastActiveSceneView != null) SceneView.lastActiveSceneView.FrameSelected(); } static float DistanceHandler(GameObject go, Vector3 p) { return (go.transform.position - p).magnitude; } static Vector3 DistanceParamHandler(string param) { if (param == "selection") { var centerPoint = Selection.gameObjects.Select(go => go.transform.position).Aggregate((v1, v2) => v1 + v2); centerPoint /= Selection.gameObjects.Length; return centerPoint; } if (param.StartsWith("[") && param.EndsWith("]")) { param = param.Trim('[', ']'); var vectorTokens = param.Split(','); var vectorValues = vectorTokens.Select(token => float.Parse(token, CultureInfo.InvariantCulture.NumberFormat)).ToList(); while (vectorValues.Count < 3) vectorValues.Add(0f); return new Vector3(vectorValues[0], vectorValues[1], vectorValues[2]); } var obj = s_GameObjects.FirstOrDefault(go => go.name == param); if (!obj) return Vector3.zero; return obj.transform.position; } static GameObject ObjectFromItem(SearchItem item) { var instanceID = Convert.ToInt32(item.id); var obj = EditorUtility.InstanceIDToObject(instanceID) as GameObject; return obj; } static Texture2D GetThumbnailForGameObject(GameObject go) { var thumbnail = PrefabUtility.GetIconForGameObject(go); if (thumbnail) return thumbnail; return EditorGUIUtility.ObjectContent(go, go.GetType()).image as Texture2D; } static Texture2D GetAssetPreviewFromPath(string path, Vector2 previewSize, FetchPreviewOptions previewOptions) { var obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path); if (obj == null) return null; var preview = AssetPreview.GetAssetPreview(obj); if (preview == null || previewOptions.HasFlag(FetchPreviewOptions.Large)) { var largePreview = AssetPreview.GetMiniThumbnail(obj); if (preview == null || (largePreview != null && largePreview.width > preview.width)) preview = largePreview; } return preview; } }
entrySeparators | Separators used to split an entry into indexable tokens. |
CreateGroupProvider | Copy of a search provider to create a new group copy. |
CreateQuery | Creates a new search query. |
CreateSceneResult | Creates a search item compatible with the scene provider. |
EnumerateAllQueries | Enumerate all user and project search queries. |
FetchGameObjects | Utility function to fetch all the game objects in a particular scene. |
FindQuery | Find a given search query given its GUID. |
FindShiftLeftVariations | Extract all variations on a word. As an example: the word hello would have the following variations: h, he, hel, hell, hello. |
FormatBytes | Formats a number into a file size in bytes string. |
FormatCount | Formats a number into a shorten number string. |
FrameAssetFromPath | Ping an asset in the project browser. |
GetAssetPath | Returns the asset path of a search item if any. |
GetAssetPreviewFromPath | Returns a preview texture to be used in the search view. |
GetAssetThumbnailFromPath | Returns a thumbnail texture to be used in the search view. |
GetHierarchyAssetPath | Get the path of the scene (or prefab) containing a GameObject. |
GetHierarchyPath | Get the hierarchy path of a GameObject including the scene name if includeScene is set to true. |
GetMainAssetInstanceID | Returns an asset instance ID. |
GetMainWindowCenteredPosition | Returns a UnityEngine.Rect to center a window on the main Unity Editor window. |
GetObjectPath | Get the path of a Unity Object. If it is a GameObject or a Component it is the . Else it is the asset name. |
GetSceneObjectPreview | Returns a scene object preview to be used in the search view. |
GetTransformPath | Format the pretty name of a Transform component by appending all the parent hierarchy names. |
GetTypeIcon | Returns a thumbnail for a given type that can be displayed in a search view. See SearchProvider.fetchThumbnail. |
MatchSearchGroups | Helper function to match a string against the SearchContext. This will try to match the search query against each token of content (similar to the AddComponent menu workflow). |
OpenQuery | Open a search view for a given query. |
PingAsset | Ping an object. |
SelectMultipleItems | Select and ping multiple objects in the Project Browser. |
ShowColumnSelector | Opens an auxiliary column selector window to allow the user to search for a column to be added. |
ShowIconPicker | Opens a search picker to select an icon. |
SplitCamelCase | Tokenize a string each capital letter. |
SplitEntryComponents | Split an entry according to a specified list of separators. |
SplitFileEntryComponents | Split a file entry according to a list of separators and find all the variations on the entry name. |
StartDrag | Utility function used to initiate a drag operation from a search view. |
TryParse | Try to parse an expression into a number. |
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.
When you visit any website, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and change our default settings. However, blocking some types of cookies may impact your experience of the site and the services we are able to offer.
More information
These cookies enable the website to provide enhanced functionality and personalisation. They may be set by us or by third party providers whose services we have added to our pages. If you do not allow these cookies then some or all of these services may not function properly.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
These cookies may be set through our site by our advertising partners. They may be used by those companies to build a profile of your interests and show you relevant adverts on other sites. They do not store directly personal information, but are based on uniquely identifying your browser and internet device. If you do not allow these cookies, you will experience less targeted advertising. Some 3rd party video providers do not allow video views without targeting cookies. If you are experiencing difficulty viewing a video, you will need to set your cookie preferences for targeting to yes if you wish to view videos from these providers. Unity does not control this.
These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.