首页 > 解决方案 > C# 统一 if 语句

问题描述

我刚开始使用unity,以前从未使用过C#。下面的代码引发了错误The name 'direction' does not exist in the current context,我不知道为什么。我确信这非常明显,但我对这一切都很陌生。

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);
}

标签: c#unity3d

解决方案


让我试着解释一下:

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);

尝试在if块之外声明:

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);
}

推荐阅读