- Home /
Breaking out of a function from an if statement inside..... Noob
Hi,
OK, what I'm trying to do, is this....
private bool moveDown = false;
private int state = 0;
void Update()
{
if( moveDown )
{
DoMyFunction();
return;
}
if( somethingElse )
{
moveDown = true;
}
}
private void DoMyFunction()
{
if( state == 0 )
{
//vector lerp blah blah bla..
state = 1;
}
if( state == 1 )
{
//vector lerp blah blah bla..
state = 2;
moveDown = false;
return;
//THIS IS WHERE I WANT TO JUMP OUT OF THE FUNCTION AND BACK TO UPDATE UNTIL moveDOWN IS TRUE AGAIN, AT WHICH POINT WE'LL START AT THE IF(STATE==2)
}
if( state == 2 )
{
//vector lerp blah blah bla..
state = 0;
moveDown = false;
return;
//BREAK OUT OF FUNCTION AGAIN UNTIL moveDOWN IS TRUE AGAIN AND START AT THE BEGINNING
}
I thought that I would be able to break out of the function with return, at which point the update would recognize moveDown as false and discontinue calling DoMyFunction until moveDown was true again. Unfortunately DoMyFunction continues to run after moveDown is declared as false..... I'm super confused!!
Can anyone help with this?
Much appreciated!!
'return' will work as you expect it to. Note that if 'somethingElse' is true, then you will only get a single frame without Do$$anonymous$$yFunction(). The code that deals with 'somethingElse' is not here, so I cannot tell if that is the problem or not.
@robertbu is right. You might be wanting an else if, or change the order, but without more context its not really possible for us to recommend anything.
On a side note, something you might find useful is the switch statement:
switch (state) {
case 1:
//Do stuff
break;
case 2:
// Do other stuff
break;
default:
Debug.LogError("Unhandled state: " + state);
break;
}
'somethingElse' was indeed the problem. Just one small thing!!
I'll try switch at some point.
Thanks guys.
Answer by highpockets · Mar 05, 2013 at 11:21 PM
'somethingElse' was indeed the problem.