错误 CS1579 foreach 语句无法对 'GameObject' 类型的变量进行操作

Error CS1579 foreach statement cannot operate on variables of type 'GameObject'

        foreach (GameObject target in targets)
        {
            objCount++;
            Animator targetAnimator = targets.GetComponent<Animator>();
            if (targetAnimator.GetInteger("Hit") == 1)
            {
                hitTargets++;
            }
        }

错误:CS1579 foreach 语句无法对类型 'GameObject' 的变量进行操作,因为 'GameObject' 不包含 'GetEnumerator'[=12= 的 public 实例或扩展定义]

因为 foreach 是实现迭代器模式的糖语法,让我们使用简单的迭代器来实现需要实现的列表或集合 IEnumerable 接口如果你想在 foreach

中使用它

根据您的错误,如果没有实现 IEnumerable 接口 (GameObject)

,则不能在 foreach 中使用 targets

也许你可以使用

objCount++;
Animator targetAnimator = targets.GetComponent<Animator>();
if (targetAnimator.GetInteger("Hit") == 1)
{
    hitTargets++;
}