I got a function that I want to call just once from OnGUI. There’re some IF, and if some condition is match, I need to call the Exit() function, that shows a GUI.Label, waits 2 secconds, and then exits. The thing is that the function is not called once, but each time OnGUI is executed. How can I solve this?
Declare a variable runonce=0;
inside OnGUI()
if(functionShouldBeCalled==1 && runonce==0) {
runYourFunc();
runonce=1;
}
if( functionNeedsToBeCalledAgain==1) {
functionShouldBeCalled=1;
runonce=0; //this will run your desired function once in next frame
}
}
You can use a state machine.
private enum State { Start, Update }
private State state;
void OnGUI() {
switch (state) {
case State.Start:
Debug.Log ("run once");
state = State.Update;
break;
case State.Update:
Debug.Log ("run every frame");
break;
}
}
void OnFocus() {
state = State.Start;
}
I’m going to try to use this to load and save xml file data. I would assume that one doesn’t want to load an xml file (or any data file for that matter) every frame.