0

I know this shouldn't be such a big issue, but for some reason a Foreach loop in a Unity project of mine won't compile. As far as I can see it follows the syntax perfectly, but Unity throws 10 syntax errors upon compilation. I've tried restarting both Unity and my computer, but the issue persists. I'd commented out the loop and the code compiled perfectly, so I know that's what's causing the issue.

Here's the full method:

List<GameObject> GetTargets()
{   
    List<GameObject> targets = new List<GameObject>();
    GameObject[] potential_targets;
    potential_targets = GameObject.FindGameObjectsWithTag("Enemy Object");
    foreach (GameObject object in potential_targets)
    {
        if (Vector2.Distance(transform.position, object.transform.position) <= firingRangeDistance)
        {
            targets.Add(object);
        }
    }
    return targets;
}

Any idea what the issue could be?

xfmw
  • 53
  • 1
  • 6
  • Can you share the error details? – Chetan May 07 '22 at 23:39
  • 1
    Try renaming `object` variable in foreach loop to something else such as `obj` – Chetan May 07 '22 at 23:42
  • @Chetan I'm guessing `object` is an attribute of the `MonoBehavior` class, because that fixed it. Thank you very much. – xfmw May 07 '22 at 23:45
  • Just in passing... when asking for help with an issue, please include the details of the errors (compiler errors (like in this case) or exception details). Also give the reader an idea of where the error occurs – Flydog57 May 08 '22 at 00:04

1 Answers1

1

I think the problem might be object is a keyword for c#, you can try to use @ to escape keyword, otherwise use other name instead of object

foreach (GameObject @object in potential_targets)
{
    if (Vector2.Distance(transform.position, @object.transform.position) <= firingRangeDistance)
    {
        targets.Add(@object);
    }
}
D-Shih
  • 44,943
  • 6
  • 31
  • 51