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

Unity中如何比对两个GameObject列表对象名称中的数字是否匹配

实现方案

针对两个GameObject列表按名称后缀数字匹配的需求,可按以下步骤实现:

核心思路

  • 抽离通用的数字提取方法,统一处理GameObject名称的数字解析逻辑
  • 按照业务场景选择匹配规则:同索引逐位比对,或忽略顺序全量匹配

代码实现

1. 适配现有代码框架的同索引比对

你的命名格式固定为前缀 数字,直接按空格分割取最后一段转整数即可,性能最高,完全贴合给出的代码结构:

using UnityEngine;
using System.Collections.Generic;
using System.Linq; // 引入LINQ以支持Last()方法

public class MatchGameObject : MonoBehaviour
{
    public List<GameObject> cube = new List<GameObject>();
    public List<GameObject> sphere = new List<GameObject>();

    void Start(){
        for(int i=0; i<cube.Count; i++){
            int cubeNum = GetNameSuffixNumber(cube[i]);
            int sphereNum = GetNameSuffixNumber(sphere[i]);
            
            if (cubeNum == sphereNum)
            {
                // 此处写匹配成功后的业务逻辑
                Debug.Log($"索引{i}匹配成功:{cube[i].name} <-> {sphere[i].name},对应数字:{cubeNum}");
            }
            else
            {
                Debug.Log($"索引{i}不匹配:{cube[i].name}(数字{cubeNum}) | {sphere[i].name}(数字{sphereNum})");
            }
        }
    }

    // 从固定格式「前缀 数字」的名称中提取末尾数字
    private int GetNameSuffixNumber(GameObject go)
    {
        string[] nameParts = go.name.Split(' ', System.StringSplitOptions.RemoveEmptyEntries);
        return int.Parse(nameParts.Last());
    }
}

2. 边缘情况适配:正则提取数字

如果存在命名不规范的情况(比如多打空格、数字前后有其他字符),可以把数字提取方法替换为正则版本,不需要严格依赖空格分割格式。需要先引入正则命名空间:

using System.Text.RegularExpressions;

替换提取方法:

private int GetNameNumber(GameObject go)
{
    Match numMatch = Regex.Match(go.name, @"\d+");
    if (numMatch.Success)
    {
        return int.Parse(numMatch.Value);
    }
    Debug.LogError($"对象[{go.name}]名称中未检测到有效数字");
    return -1; // 提取失败返回无效值标记
}

3. 可选:忽略列表顺序的全量匹配

如果不需要按索引比对,而是要找出所有数字相同的跨位置匹配对,可以用字典做映射避免嵌套循环,性能更高:

void Start(){
    Dictionary<int, GameObject> sphereMap = new Dictionary<int, GameObject>();
    foreach (GameObject sp in sphere)
    {
        int num = GetNameSuffixNumber(sp);
        sphereMap.TryAdd(num, sp); // 重复数字只保留第一个,可根据业务调整
    }

    foreach (GameObject cb in cube)
    {
        int cubeNum = GetNameSuffixNumber(cb);
        if (sphereMap.TryGetValue(cubeNum, out GameObject matchedSp))
        {
            Debug.Log($"匹配成功:{cb.name} <-> {matchedSp.name},对应数字:{cubeNum}");
        }
    }
}

注意:以上代码默认名称里的数字为合法整数,如果存在非数字字符、数字超出int范围的情况,可以用int.TryParse替代int.Parse做异常捕获,避免运行时报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 04:24:23