版本:Unity 6 (6000.0)
语言中文
  • C#

SearchIndexer.resolveDocumentHandler

提出修改建议

提交成功!

感谢您帮助我们提高 Unity 文档质量。虽然我们无法接受所有提交,但我们会阅读用户提出的每一项修改建议,并在适用时进行更新。

关闭

提交失败

由于某些原因,您建议的修改无法提交。请在几分钟后再重试。感谢您抽出时间帮助我们提高 Unity 文档质量。

关闭

取消

public Func<string,string> resolveDocumentHandler;

说明

用来将文档 ID 解析成其他数据字符串的处理程序。

using System.Linq;
using UnityEditor;
using UnityEditor.Search;
using UnityEngine;

/// <summary>
/// Since the search indexes only contain string document IDs that must be unique,
/// you can use `resolveDocumentHandler` to transform these document IDs into something
/// that can be searched while running queries that contain simple words.
/// </summary>
static class Example_SearchIndexer_resolveDocumentHandler
{
    struct Weapon
    {
        public string id { get; private set; }
        public int power { get; set; }
        public string name { get; set; }

        public Weapon(string name, int power)
        {
            id = System.Guid.NewGuid().ToString("N");
            this.name = name;
            this.power = power;
        }
    }

    [MenuItem("Examples/SearchIndexer/resolveDocumentHandler")]
    public static void Run()
    {
        const int MagicPower = 1;
        var weapons = new[]
        {
            new Weapon("Long Bow", 2),
            new Weapon("Short Sword", 3),
            new Weapon("Short Sword", 3 + MagicPower), // We have two weapons that will have different ids, but the same name.
            new Weapon("Long Sword", 4)
        };
        var si = new SearchIndexer("Weapons")
        {
            // Define a handler that returns a searchable string that can search for each document.
            // These words are not indexed, therefore the string is linear and might not scale as expected.
            // IMPORTANT: Unless you want to have case-sensitive search, you should convert the resolved string to lowercase.
            resolveDocumentHandler = (id) => weapons.First(w => w.id == id).name.ToLowerInvariant()
        };

        si.Start();
        foreach (var w in weapons)
        {
            var di = si.AddDocument(w.id);
            si.AddWord("weapon", 0, di);
        }
        si.Finish(() => OnIndexReady(si, weapons));
    }

    private static void OnIndexReady(SearchIndexer si, Weapon[] weapons)
    {
        var results = si.Search("weapon sword").ToArray();
        Debug.Assert(results.Length == 3, "No weapon were found");
        foreach (var result in results)
        {
            var w = weapons.First(w => w.id == result.id);
            Debug.Log($"Found [{result.index}] {result.id}/{w.name} ({w.power})");
        }
    }
}