# SearchUtils

> Provides various utility functions that are used by SearchProvider.

## Definition

* **Type:** Class
* **Namespace:** [UnityEditor.Search](/engine/6000.6/script-reference/unityeditor/search.md)
* **Assembly:** UnityEditor

```csharp
public static class SearchUtils
```

## Examples

```csharp
using System;
using System.Collections;
using System.Globalization;
using System.Linq;
using Unity.Collections.LowLevel.Unsafe;
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,
        };
    }

    #region OnEnable
    static void OnEnable()
    {
        s_GameObjects = SearchUtils.FetchGameObjects().ToArray();
        s_QueryEngine = new QueryEngine<GameObject>();

        // Id supports all operators
        s_QueryEngine.AddFilter("id", go => go.GetEntityId());
        // 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[] {"=", "!=", "<", ">", "<=", ">="});
    }

    #endregion

    #region SearchItems
    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.GetEntityId().ToString(), null, null, null, filteredObject.GetEntityId());
        }
    }

    #endregion

    #region FetchLabel
    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;
    }

    #endregion

    #region FetchDescription
    static string FetchDescription(SearchItem item, SearchContext context)
    {
        var go = ObjectFromItem(item);
        return (item.description = SearchUtils.GetHierarchyPath(go));
    }

    #endregion

    static Texture2D FetchThumbnail(SearchItem item, SearchContext context)
    {
        var obj = ObjectFromItem(item);
        if (obj == null)
            return null;

        return item.thumbnail = GetThumbnailForGameObject(obj);
    }

    #region FetchPreview
    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);
    }

    #endregion

    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)
    {
        ulong id = Convert.ToUInt64(item.id);
        var entityId = UnsafeUtility.As<ulong, EntityId>(ref id);
        var obj = EditorUtility.EntityIdToObject(entityId) 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;
    }
}
```

## Static Fields

| Value                                                                                                | Description                                              |
| ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| [entrySeparators](/engine/6000.6/script-reference/unityeditor/search/searchutils/entryseparators.md) | Separators used to split an entry into indexable tokens. |

## Static Methods

| Method                                                                                                                           | Description                                                                                                                                                                                                                                                            |
| -------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [CreateGroupProvider](/engine/6000.6/script-reference/unityeditor/search/searchutils/creategroupprovider.md)                     | Copy of a search provider to create a new group copy.                                                                                                                                                                                                                  |
| [CreateQuery](/engine/6000.6/script-reference/unityeditor/search/searchutils/createquery.md)                                     | Creates a new search query.                                                                                                                                                                                                                                            |
| [CreateSceneResult](/engine/6000.6/script-reference/unityeditor/search/searchutils/createsceneresult.md)                         | Creates a search item compatible with the scene provider.                                                                                                                                                                                                              |
| [EnumerateAllQueries](/engine/6000.6/script-reference/unityeditor/search/searchutils/enumerateallqueries.md)                     | Enumerate all user and project search queries.                                                                                                                                                                                                                         |
| [FetchGameObjects](/engine/6000.6/script-reference/unityeditor/search/searchutils/fetchgameobjects.md)                           | Utility function to fetch all the game objects in a particular scene.                                                                                                                                                                                                  |
| [FindQuery](/engine/6000.6/script-reference/unityeditor/search/searchutils/findquery.md)                                         | Find a given search query given its GUID.                                                                                                                                                                                                                              |
| [FindShiftLeftVariations](/engine/6000.6/script-reference/unityeditor/search/searchutils/findshiftleftvariations.md)             | Extract all variations on a word. As an example: the word hello would have the following variations: h, he, hel, hell, hello.                                                                                                                                          |
| [FormatBytes](/engine/6000.6/script-reference/unityeditor/search/searchutils/formatbytes.md)                                     | Formats a number into a file size in bytes string.                                                                                                                                                                                                                     |
| [FormatCount](/engine/6000.6/script-reference/unityeditor/search/searchutils/formatcount.md)                                     | Formats a number into a shorten number string.                                                                                                                                                                                                                         |
| [FrameAssetFromPath](/engine/6000.6/script-reference/unityeditor/search/searchutils/frameassetfrompath.md)                       | Ping an asset in the project browser.                                                                                                                                                                                                                                  |
| [GetAssetPath](/engine/6000.6/script-reference/unityeditor/search/searchutils/getassetpath.md)                                   | Returns the asset path of a search item if any.                                                                                                                                                                                                                        |
| [GetAssetPreviewFromPath](/engine/6000.6/script-reference/unityeditor/search/searchutils/getassetpreviewfrompath.md)             | Returns a preview texture to be used in the search view.                                                                                                                                                                                                               |
| [GetAssetThumbnailFromPath](/engine/6000.6/script-reference/unityeditor/search/searchutils/getassetthumbnailfrompath.md)         | Returns a thumbnail texture to be used in the search view.                                                                                                                                                                                                             |
| [GetHierarchyAssetPath](/engine/6000.6/script-reference/unityeditor/search/searchutils/gethierarchyassetpath.md)                 | Get the path of the scene (or prefab) containing a GameObject.                                                                                                                                                                                                         |
| [GetHierarchyPath](/engine/6000.6/script-reference/unityeditor/search/searchutils/gethierarchypath.md)                           | Get the hierarchy path of a GameObject including the scene name if includeScene is set to true.                                                                                                                                                                        |
| [GetMainAssetEntityId](/engine/6000.6/script-reference/unityeditor/search/searchutils/getmainassetentityid.md)                   | Returns an asset EntityId.                                                                                                                                                                                                                                             |
| [GetMainWindowCenteredPosition](/engine/6000.6/script-reference/unityeditor/search/searchutils/getmainwindowcenteredposition.md) | Returns a [Rect](/engine/6000.6/script-reference/unityengine/rect.md) to center a window on the main Unity Editor window.                                                                                                                                              |
| [GetObjectPath](/engine/6000.6/script-reference/unityeditor/search/searchutils/getobjectpath.md)                                 | Get the path of a Unity Object. If it is a GameObject or a Component it is the [SearchUtils.GetTransformPath(Transform)](/engine/6000.6/script-reference/unityeditor/search/searchutils/gettransformpath.md#gettransformpath\(transform\)). Else it is the asset name. |
| [GetSceneObjectPreview](/engine/6000.6/script-reference/unityeditor/search/searchutils/getsceneobjectpreview.md)                 | Returns a scene object preview to be used in the search view.                                                                                                                                                                                                          |
| [GetTransformPath](/engine/6000.6/script-reference/unityeditor/search/searchutils/gettransformpath.md)                           | Format the pretty name of a Transform component by appending all the parent hierarchy names.                                                                                                                                                                           |
| [GetTypeIcon](/engine/6000.6/script-reference/unityeditor/search/searchutils/gettypeicon.md)                                     | Returns a thumbnail for a given type that can be displayed in a search view. See [SearchProvider.fetchThumbnail](/engine/6000.6/script-reference/unityeditor/search/searchprovider/fetchthumbnail.md).                                                                 |
| [MatchSearchGroups](/engine/6000.6/script-reference/unityeditor/search/searchutils/matchsearchgroups.md)                         | 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](/engine/6000.6/script-reference/unityeditor/search/searchutils/openquery.md)                                         | Open a search view for a given query.                                                                                                                                                                                                                                  |
| [PingAsset](/engine/6000.6/script-reference/unityeditor/search/searchutils/pingasset.md)                                         | Ping an object.                                                                                                                                                                                                                                                        |
| [SelectMultipleItems](/engine/6000.6/script-reference/unityeditor/search/searchutils/selectmultipleitems.md)                     | Select and ping multiple objects in the Project Browser.                                                                                                                                                                                                               |
| [ShowColumnSelector](/engine/6000.6/script-reference/unityeditor/search/searchutils/showcolumnselector.md)                       | Opens an auxiliary column selector window to allow the user to search for a column to be added.                                                                                                                                                                        |
| [ShowIconPicker](/engine/6000.6/script-reference/unityeditor/search/searchutils/showiconpicker.md)                               | Opens a search picker to select an icon.                                                                                                                                                                                                                               |
| [SplitCamelCase](/engine/6000.6/script-reference/unityeditor/search/searchutils/splitcamelcase.md)                               | Tokenize a string each capital letter.                                                                                                                                                                                                                                 |
| [SplitEntryComponents](/engine/6000.6/script-reference/unityeditor/search/searchutils/splitentrycomponents.md)                   | Split an entry according to a specified list of separators.                                                                                                                                                                                                            |
| [SplitFileEntryComponents](/engine/6000.6/script-reference/unityeditor/search/searchutils/splitfileentrycomponents.md)           | Split a file entry according to a list of separators and find all the variations on the entry name.                                                                                                                                                                    |
| [StartDrag](/engine/6000.6/script-reference/unityeditor/search/searchutils/startdrag.md)                                         | Utility function used to initiate a drag operation from a search view.                                                                                                                                                                                                 |
| [TryParse](/engine/6000.6/script-reference/unityeditor/search/searchutils/tryparse.md)                                           | Try to parse an expression into a number.                                                                                                                                                                                                                              |
