- Home /
why does if statement ignore bool?
Hey guys i am trying to make a background in a 2D game which slowly scrolls but i am making a transition to enter a new world but it seems like unity just ignores my bool in the if statement?? anyone know how come?
the script is attached to two different pictures which then scrolls
float moveSpeed = -0.02f;
float World2 = 20f;
float maxHeight = 0f;
bool transition = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Translate (0, moveSpeed, 0);
maxHeight = renderer.bounds.size.y;
Vector3 pos = transform.position;
if (-maxHeight >= pos.y) {
pos.y = +maxHeight + moveSpeed;
transform.position = pos;
}
if (Score.score >= World2) {
if (pos.y >= 11.42f && transition == false){
Debug.Log ("HALLLO!!!!!");
gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load("World2Trans", typeof(Sprite)) as Sprite;
Vector3 scale = transform.localScale;
scale.y = 1.01f;
transform.localScale = scale;
transition = true;
}
if (pos.y >= 11.42f && transition == true){
gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load("World2", typeof (Sprite)) as Sprite;
}
}
}
}
Answer by Tehnique · Jul 21, 2014 at 09:25 AM
The "&&" operator short-circuits. That means that if the first expression is False, it does not evaluate the second. Same happens to "||" (if first expression is True, second is not evaluated). More here.
If you really want to evaluate both expressions, you can use &. Although, that makes no sense in your case (it's better suited if your second condition also runs some code you want to run regardless of the logical outcome).
Also, I'd refactor your code like this:
if (Score.score >= World2 && pos.y >= 11.42f)
{
if (!transition)
{
Debug.Log ("HALLLO!!!!!");
gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load("World2Trans", typeof(Sprite)) as Sprite;
Vector3 scale = transform.localScale;
scale.y = 1.01f;
transform.localScale = scale;
transition = true;
}
else
{
gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load("World2", typeof (Sprite)) as Sprite;
}
}
Also, you have no code that resets "transition" once it's been set to true. Maybe you should look into that, too.
Thank you for your answer! i realised that with two if statements it just went trough the first sprite and in the same frame run the second if, so i made an else if statement which sort of worked, but then the transition sprite i made, came twice. Then i realized that was because it was two different scripts. i then made the bool public, and made the script check for the bool on the other script and now it works :)
yes i will certainly look into making the bool false again, but after 2 hours not knowing what to do i just had to finish the transition logic before i cleaned up the code properly :) thanks again!