0

I have just started with unity, and have never used C# before. The code below raises the error The name 'direction' does not exist in the current context and I have no clue why. I'm sure it's super obvious but I am new to all this.

float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");

if (moveVertical != 0 || moveHorizontal != 0) {
    if (moveVertical > 0) {
        string direction = "up";
    } else if (moveVertical < 0) {
        string direction = "down";
    } else if (moveHorizontal > 0) {
        string direction = "right";
    } else if (moveHorizontal < 0) {
        string direction = "left";
    } else {
        string direction = "###";
    }

    Debug.Log(direction);
}

1 Answers1

4

Let me try to explain a bit:

if (moveVertical > 0) {
    // You are declaring this for the if block
    // This is declared locally here
    string direction = "up";
    // Direction exists in the if block
    Debug.Log(direction);
}
// Direction does not exist here as it is out of the block
Debug.Log(direction);

Try to declare outside of the if blocks:

float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
string direction = "";

if (moveVertical != 0 || moveHorizontal != 0) {
    if (moveVertical > 0) {
        direction = "up";
    } else if (moveVertical < 0) {
        direction = "down";
    } else if (moveHorizontal > 0) {
        direction = "right";
    } else if (moveHorizontal < 0) {
        direction = "left";
    } else {
        direction = "###";
    }

    Debug.Log(direction);
}
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61