You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让GUILayout.TextField实现大小写不敏感的搜索功能?

解决Unity编辑器搜索功能大小写不匹配问题

你的搜索功能出现大小写区分问题,根源是C#原生string.Contains()方法默认区分大小写。要实现不区分大小写的搜索,有两种直接的修改方式:

方法一:统一转换为小写(或大写)后匹配

把搜索关键词和目标字符串都转成小写,再用Contains()判断,就能忽略大小写差异:

修改代码中的匹配逻辑部分:

if (!string.IsNullOrEmpty(searchString)) // 替换原判断,同时处理空字符串场景
{
    // 统一转小写后判断包含关系
    if (pair.Value.ToLower().Contains(searchString.ToLower()))
    {
        EditorGUILayout.ObjectField(pair.Key, typeof(GameObject), true);
        num.Add(EditorGUILayout.TextField(pair.Value).Length);
    }
}

方法二:使用不区分大小写的IndexOf判断

用string.IndexOf()方法并指定StringComparison.OrdinalIgnoreCase参数,无需转换字符串,性能更优:

修改后的匹配逻辑:

if (!string.IsNullOrEmpty(searchString))
{
    // 通过IndexOf指定忽略大小写规则
    if (pair.Value.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
    {
        EditorGUILayout.ObjectField(pair.Key, typeof(GameObject), true);
        num.Add(EditorGUILayout.TextField(pair.Value).Length);
    }
}

修改后的完整代码

string searchString;
Vector2 scrollPos;
List<int> num = new List<int>();
Dictionary<GameObject, string> dictio;

void OnGUI()
{
    GUI.color = Color.white;

    GUILayout.FlexibleSpace();
    searchString = GUILayout.TextField(searchString, GUI.skin.FindStyle("ToolbarSeachTextField"));
    if (GUILayout.Button("", GUI.skin.FindStyle("ToolbarSeachCancelButton")))
    {
        searchString = "";
        GUI.FocusControl(null);
    }

    scrollPos =
        EditorGUILayout.BeginScrollView(scrollPos, false, true,
        GUILayout.ExpandWidth(true), GUILayout.Height(position.height));

    foreach (KeyValuePair<GameObject, string> pair in dictio)
    {
        EditorGUILayout.BeginHorizontal();

        if (!string.IsNullOrEmpty(searchString))
        {
            // 此处使用方法二的实现,可按需替换为方法一代码
            if (pair.Value.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
            {
                EditorGUILayout.ObjectField(pair.Key, typeof(GameObject), true);
                num.Add(EditorGUILayout.TextField(pair.Value).Length);
            }
        }

        EditorGUILayout.EndHorizontal();
    }

    GUILayout.EndScrollView();
}

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 08:25:20