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

如何遍历嵌套数组?Unity序列化类下的条件遍历实现问询

实现方法说明

首先先修正你代码里的几个拼写/类型错误,不然编译会报错:

  • enumEnumType 应该改为 EnumType(假设你已经定义了这个枚举)
  • Class1Values[] 应该改为 Class1[],因为你定义的类是Class1,数组类型要对应
  • Class2Values[] 应该改为 Class2[],同理类是Class2

修正后的代码如下:

[Serializable]
class Class1
{   
    [Range(0f, 1f)]
    public float Height;
    public EnumType EnumType; // 修正枚举名称
}

private Class1[] Class1Types; // 修正数组类型

[Serializable]
class Class2
{   
    [Range(0f, 1f)]
    public float Height;
    public Class1[] Class1Values; // 修正数组类型
  
}

[SerializeField]
private Class2[] Class2Types; // 修正数组类型

接下来按照你的需求实现遍历逻辑,核心是两层嵌套循环:外层遍历Class2Types的每个元素,内层遍历每个Class2元素里的Class1Values数组,然后根据Height的特定值执行对应操作。

具体实现代码

// 先判断数组是否为空,避免空引用异常
if (Class2Types == null) return;

// 遍历外层Class2Types数组
foreach (var class2Item in Class2Types)
{
    // 判断当前Class2元素的Height值(浮点数用Approximately避免精度问题)
    if (Mathf.Approximately(class2Item.Height, 10f))
    {
        // 先判断内部数组是否为空
        if (class2Item.Class1Values == null) continue;
        
        // 遍历当前Class2元素内部的Class1Values数组
        foreach (var class1Item in class2Item.Class1Values)
        {
            if (Mathf.Approximately(class1Item.Height, 10f))
            {
                // 执行Height=10时的操作
                DoSomethingFor10And10();
            }
            else if (Mathf.Approximately(class1Item.Height, 5f))
            {
                // 执行Height=5时的操作
                DoSomethingElseFor10And5();
            }
        }
    }
    else if (Mathf.Approximately(class2Item.Height, 5f))
    {
        if (class2Item.Class1Values == null) continue;
        
        foreach (var class1Item in class2Item.Class1Values)
        {
            if (Mathf.Approximately(class1Item.Height, 10f))
            {
                // 执行对应操作
                DoSomethingFor5And10();
            }
            else if (Mathf.Approximately(class1Item.Height, 5f))
            {
                // 执行对应操作
                DoSomethingElseFor5And5();
            }
        }
    }
}

// 示例操作方法,替换成你的实际逻辑即可
void DoSomethingFor10And10()
{
    // 你的操作逻辑
}

void DoSomethingElseFor10And5()
{
    // 你的操作逻辑
}

void DoSomethingFor5And10()
{
    // 你的操作逻辑
}

void DoSomethingElseFor5And5()
{
    // 你的操作逻辑
}

关键注意点

  • 浮点数比较:直接用==比较float类型容易出现精度误差,Unity里推荐用Mathf.Approximately(a, b)判断两个浮点数是否近似相等。
  • 空值防护:必须对数组做null判断,避免运行时抛出空引用异常。
  • Range属性冲突:你给Height加了[Range(0f,1f)]限制,但示例里用了10、5这类超出范围的值,如果需要使用这些值,要去掉该属性或调整Range的范围。

内容的提问来源于stack exchange,提问作者Григорій

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:45:37