if condition not working

public class canonControl : MonoBehaviour {

bool deployed;

void Awake() {
    deployed = false;
}

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

    if((Input.GetButtonUp("Canon")) && deployed == false) {
        animation.Play("canon_deploy");
        deployed = true;
    }

    if ((Input.GetButtonUp("Canon")) && deployed == true) {
        animation.Play("canon_undeploy");
        deployed = false;
    }

}

for a reason it is not working, it always play undeploy animation. Can any one please help me.

2 Answers

2

Stick an else before the second if

At the moment your code will immediately meet the second condition if it met the first condition (read it and see!)

This is because both if statements are true in sequence since you change the value of deployed. Try the following instead:

bool deployed;

void Update() {
    if (Input.GetButtonUp("Canon")) {
        // Toggle state of deployment.
        deployed = !deployed;

        // Play desired animation.
        if (deployed)
            animation.Play("canon_deploy");
        else
            animation.Play("canon_undeploy");
    }
}

Thanks for the help