忽略具有触发的if语句的代码

时间:2017-07-29 17:30:30

标签: c# if-statement unity3d

这是根据按下的键切换图像用户界面精灵图像的代码:

using UnityEngine;
using UnityEngine.UI;

public class ImageController : MonoBehaviour {
    public Sprite left;
    public Sprite topleft;
    public Sprite backleft;
    public Sprite right;
    public Sprite topright;
    public Sprite backright;
    public Sprite top;
    public Sprite back;
    public Sprite nothing;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.UpArrow))
        {
            if (Input.GetKey(KeyCode.LeftArrow))
            {
                Debug.Log("HI");                          // Not ignored??
                GetComponent<Image>().sprite = topleft;   // Ignored
            }
            if (Input.GetKey(KeyCode.RightArrow))
            {
                GetComponent<Image>().sprite = topright;
            }
            else
            {
                GetComponent<Image>().sprite = top;
            }
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            if (Input.GetKey(KeyCode.LeftArrow))
            {
                GetComponent<Image>().sprite = backleft;
            }
            if (Input.GetKey(KeyCode.RightArrow))
            {
                GetComponent<Image>().sprite = backright;
            }
            else
            {
                GetComponent<Image>().sprite = back;
            }
        }
    }
}

第一个嵌套if语句中的代码(在本例中为if (Input.GetKey(KeyCode.LeftArrow)) {})将不起作用(图像不会更改)。我在两个if语句中添加了Debug.Log("HI")以查看它是否有效。改变条件也行不通。但是所有其他嵌套的if语句都能正常工作。另请注意,图像已正确放置在Unity编辑器中。

那么为什么尽管GetComponent<Image>().sprite = topleft;语句&#39}完全忽略了行if。条件都满足了?

1 个答案:

答案 0 :(得分:0)

            GetComponent<Image>().sprite = topleft;   // Ignored

它没有被忽视。该值按预期分配,但稍后会被top覆盖,因为您else执行的LeftArrow 始终

        // Assign as the default value first.
        GetComponent<Image>().sprite = top;

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            GetComponent<Image>().sprite = topleft; 
        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            GetComponent<Image>().sprite = topright;
        }