I am trying to show a simple GUI Lable for 1 second after a button has been pressed. I ran the following, and Unity just froze. Is my while loop OK?
var test = false;
function OnGUI () {
var timeWhenPushed;
// Make a background box
GUI.Box (Rect (10,10,100,90), "GUI Basics");
// Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
if (GUI.Button (Rect (20,40,80,20), "Level 1")) {
print( "you hit LoadLevel (1), but this does nothing yet");
test = true;
timeWhenPushed = Time.time;
print ("You pushed the button at " + timeWhenPushed);
while (Time.time <= timeWhenPushed +1)
{
GUI.Label(Rect (120, 40, 200, 40), "You hit level 1");
}
}
if (test == true)
{
//If (Time.time <= timeWhenPushed + 1)
//{
GUI.Label(Rect (120, 70, 200, 40), "You hit level 1");
//}
}
// Make the second button.
//if (GUI.Button (Rect (20,70,80,20), GUIContent ("Level 2", "This is the tooltip")));
if (GUI.Button (Rect (20,70,80,20), GUIContent("Level 2", "Yep - tooltip")))
{
print ("You hit LoadLevel (2), but this does nothing yet");
}
}
Mike_3
2
No, the while loop isn't ok like that. It'll just block unity indefinitely - even if the Time.time variable was updated, you'd just stop unity running until the right time.
My guess is you want to start a coroutine which sets a bool (which you check to show the label), wait, then unset the bool
Edit:
change this
if (GUI.Button (Rect (20,40,80,20), "Level 1"))
{
print( "you hit LoadLevel (1), but this does nothing yet");
test = true;
timeWhenPushed = Time.time;
print ("You pushed the button at " + timeWhenPushed);
while (Time.time <= timeWhenPushed +1)
{
GUI.Label(Rect (120, 40, 200, 40), "You hit level 1");
}
}
to this:
if (GUI.Button (Rect (20,40,80,20), "Level 1"))
{
print( "you hit LoadLevel (1), but this does nothing yet");
test = true;
timeWhenPushed = Time.time;
print ("You pushed the button at " + timeWhenPushed);
}
if (Time.time <= timeWhenPushed +1)
{
GUI.Label(Rect (120, 40, 200, 40), "You hit level 1");
}