代码检查:不支持 'foreach' 结构
此检查报告 foreach 循环出现在由 Burst 编译器编译的代码中。
Burst 不支持 foreach 结构,即使在遍历与 Burst 兼容的数据(如原生容器)时也是如此。
示例
在此示例中, foreach 循环用于在 Burst 编译的作业中遍历 NativeArray<int>。 此不受支持并会被标记。
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
[BurstCompile]
public struct ExampleJob : IJob
{
public NativeArray<int> values;
public void Execute()
{
// Reported: foreach is not supported in Burst
foreach (var value in values)
{
}
}
}
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
[BurstCompile]
public struct ExampleJob : IJob
{
public NativeArray<int> values;
public void Execute()
{
// Correct: Replace foreach with an index-based loop
for (var i = 0; i < values.Length; i++)
{
var value = values[i];
}
}
}
2026年 5月 8日