Check If Transform.Position.x In Array Equals Tree.Transform.Position.x

Trying to see if all enemies in array transform.position.x is treeLeft.x. Just one big check instead of doing each individually. but I get the (CS0136 error: “error CS0136: A local or parameter named ‘enemy’ cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter”) every time I use the .All method. Any Help would be appreciated Thanks, Here’s A Part Of The Code. I want the enemy to move something like this but, my last code was to CPU dependent I can show you if you’d like to see. .Hobo Brawl

private void CheckIfOtherEnemiesCanGoTreeLeft()
{
    if (transform.position.x == treeLeftSide.x)
    {
        foreach (AIMovementMelee enemy in enemiesOnLevel)
        {
            if (enemy.transform.position.x != treeLeftSide.x)
            {
                enemy.SetCanGoTreeLeft(false);
                //Go To Right Side If It's Avail else Don't Go To Right
                var allEnemiesNotAtRight = enemiesOnLevel.All(enemy => enemy.transform.position.x != treeRightSide.x);
                if (allEnemiesNotAtRight)
                {
                    enemy.SetCanGoTreeRight(true);
                }
                else
                {
                    enemy.SetCanGoTreeRight(false);
                }
            }
        }
    }
    else
    {
        //Set All Enemies canGoTreeLeft true If No Enemy At Left Side
        var noEnemyAtLeft = enemiesOnLevel.All(enemy => enemy.transform.position.x != treeLeftSide.x);
        if (noEnemyAtLeft)
        {
            foreach (AIMovementMelee enemy in enemiesOnLevel)
            {
                enemy.SetCanGoTreeLeft(true);
            }
        }
    }
}

Hi @Wonders_Of_Life,

Welcome to our community! :slight_smile:

In which course and lecture are you?

Sorry for the late response. It’s not something in the Unity: 2D course, it’s an issue I’ve been trying to figure out.

Hey!

I might be mistaken, but I think you are defining “enemy” twice in the same scope, so C# doesn’t like that.

Here:

foreach (AIMovementMelee enemy in enemiesOnLevel)
        { ...

And then here:

var allEnemiesNotAtRight = enemiesOnLevel.All(enemy => enemy.transform.position.x != treeRightSide.x);

So for C#, you already have a variable named “enemy” so you can’t reuse that name in the All method I think.

Maybe when you use the All() method, try to call your variable in the parameter differently (like “elem” for element or “item”)

Hope this help.

PS: I don’t know how versed you are in programing, if you need help understanding the concept of scope in variable declaration, I can tell you the little that I know :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms