- Home /
Call a function once from OnGUI
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?
what I would do is add a boolean with the IF that you're talking about. When the if is executed make ur boolean false. if(someboolean && somecoditionmatched) someboolean = false;
so you basically want a pop up message that stays on screen for 2 seconds, right?
and to run GUI once, just set that bool true, and then instantly to false.
I did the boolean solution but I was thinking that may be there're was an ad hoc solution! Something like InvokeOnce!
Answer by Srimasis · Aug 31, 2013 at 07:04 PM
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
}
}
Answer by astracat111 · Apr 17, 2017 at 01:18 PM
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.
Your answer
Follow this Question
Related Questions
touch buttons function OnGUI issue 1 Answer
Why doesen't the function get called the second itme? 1 Answer
How do i delay function Update 3 Answers
Help with If statement INSIDE if statement!! 2 Answers
Update increment error (2 + 1 = 0?) 1 Answer