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

Time:04-23

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

Error: CS1579 foreach statement cannot operate on variables of type 'GameObject' because 'GameObject' does not contain a public instance or extension definition for 'GetEnumerator'

CodePudding user response:

Because foreach is a sugar syntax to implement an iterator pattern let's use easy iterator a list or collection that needs to implement IEnumerable interface if you want to use it in foreach

From your error, you can't use targets in foreach if that didn't implement IEnumerable interface (GameObject)

Maybe you can use

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