-4

I have an error saying: (error CS0136: A local or parameter named 'facingRight' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter). I'm a kind of new to this so I don't know what it says and I haven't been able to find anything about it online. It would be nice if any of you could help me out here

I'm trying to make an animation flip in Unity, but I don't specifically remember what I've tried

    bool facingRight = true;
    bool facingLeft = false;

    if (facingRight == true && facingLeft == false)
    {
        if (Input.GetKey("a"))
        {
            transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
            bool facingRight = true;
            bool facingLeft = false;
        }
    }

    if (facingLeft == true && facingRight == false)
    {
        if (Input.GetKey("a"))
        {
            transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
            bool facingLeft = true;
            bool facingRight = false;
        }
    }

The expected result is for my animation to turn around when pressing the a key and then when pressing the d key it turns around again.

1 Answers1

3

It is because you already declared the variables.

Remove the bool from the inner scopes in if:

bool facingLeft = true;
bool facingRight = false;

And add a else between the if to avoid collision.

But perhaps you better want to use differents names to have a better code smell, depending of the goal.

C# Variable Scopes

  • 2
    The reason why this works is because `bool` is declaring a new variable, whereas without it you're just _assigning to_ the variable further up in the scope. – Jacob Oct 09 '19 at 20:11