Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why won't my foreach loop compile in Unity?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading