samedi 29 juillet 2017

Code with triggered if statement is ignored

This is the code where an Image UI's sprite image is switched depending on key(s) pressed down:

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

The code within the first nested if statement (in this case, if (Input.GetKey(KeyCode.LeftArrow)) {}) will not work (the image will not change). I have added Debug.Log("HI") in both if statements to see if it works and it does. Changing the conditions also does not work. All other nested if statements work properly though.

So why is the line GetComponent<Image>().sprite = topleft; being completely ignored though the if statements' conditions are all met?

Aucun commentaire:

Enregistrer un commentaire