obsidian/笔记文件/2.笔记/unity编辑器检索关键文本,跳转到代码位置怎么写.md
2025-03-26 00:02:56 +08:00

3.4 KiB
Raw Permalink Blame History

#unity/日常积累

在 Unity 编辑器中实现检索关键文本并跳转到代码位置的功能,可以通过自定义编辑器脚本和使用 AssetDatabase 来实现。下面是一个示例,演示如何创建一个简单的编辑器窗口,允许用户输入关键字并在项目中查找相关脚本,然后跳转到相应的位置。

示例代码

using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;

public class KeywordSearcher : EditorWindow
{
    private string searchKeyword = "";
    private List<string> results = new List<string>();

    [MenuItem("Window/Keyword Searcher")]
    public static void ShowWindow()
    {
        GetWindow<KeywordSearcher>("Keyword Searcher");
    }

    private void OnGUI()
    {
        GUILayout.Label("Search for Keyword in Scripts", EditorStyles.boldLabel);

        // 输入框
        searchKeyword = EditorGUILayout.TextField("Keyword:", searchKeyword);

        // 按钮
        if (GUILayout.Button("Search"))
        {
            SearchForKeyword();
        }

        // 显示搜索结果
        foreach (var result in results)
        {
            if (GUILayout.Button(result))
            {
                OpenFileAtLine(result);
            }
        }
    }

    private void SearchForKeyword()
    {
        results.Clear();
        string[] allScripts = Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories);

        foreach (var script in allScripts)
        {
            string content = File.ReadAllText(script);
            if (content.Contains(searchKeyword))
            {
                results.Add(script);
            }
        }
    }

    private void OpenFileAtLine(string path)
    {
        string relativePath = "Assets" + path.Substring(Application.dataPath.Length);
        UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(relativePath, 1);
    }
}

代码说明

  1. 创建窗口

    • 使用 EditorWindow 创建一个新的窗口,用户可以在其中输入关键字。
  2. 输入框

    • EditorGUILayout.TextField 用于输入关键字。
  3. 搜索按钮

    • 当用户点击 "Search" 按钮时,调用 SearchForKeyword 方法来查找所有脚本中包含该关键字的文件。
  4. 搜索逻辑

    • 使用 Directory.GetFiles 获取所有 .cs 文件,读取文件内容并检查是否包含关键字。如果找到,则将文件路径添加到结果列表中。
  5. 显示结果

    • 使用 GUILayout.Button 显示搜索结果,用户可以点击结果以打开文件。
  6. 打开文件

    • OpenFileAtLine 方法使用 InternalEditorUtility.OpenFileAtLineExternal 来打开指定的脚本文件。此处的行数设为 1您可以根据需求更改。

使用方法

  1. 将上述代码保存为 KeywordSearcher.cs 文件,放在 Editor 文件夹中(如 Assets/Editor/)。
  2. 在 Unity 编辑器中,点击 Window > Keyword Searcher 打开窗口。
  3. 输入想要搜索的关键字,点击 Search,结果会显示在窗口中。
  4. 点击任何结果Unity 将打开相应的脚本文件。

注意事项

  • 该示例仅支持简单的文本匹配,实际开发中可能需要更复杂的解析和处理。
  • 该窗口会搜索所有 .cs 文件,可能会影响性能,尤其在大型项目中。根据需要进行优化。