- Home /
Drawing a box from a button click
For the life of me, I can't work out why this isn't working, the button should draw a box when it's clicked, but it isn't working?
Any ideas?
using UnityEngine;
using System.Collections;
public class Gui : MonoBehaviour {
void OnGUI() {
var boxcheck1 = false;
if (GUI.Button(new Rect(250, 700, 90, 20), "Campaign")){
boxcheck1 = true;
Debug.Log("boxcheck1 = true");
}
if (boxcheck1 == true)
{
GUI.Box(new Rect(10, 10, 800, 600), "");
}
}
}
Answer by robertbu · May 28, 2013 at 01:21 PM
GUI.Button() only returns true for a single frame (on the mouse up). Your variable 'boxcheck1' is local OnGUI() so it gets reset to false each time OnGUI() is called. So you box does show...for a single frame (which is too fast to see). One fix is to move 'boxcheck1' outside of OnGUI():
using UnityEngine;
using System.Collections;
public class Gui : MonoBehaviour {
bool boxcheck1 = false;
void OnGUI() {
if (GUI.Button(new Rect(250, 700, 90, 20), "Campaign")){
boxcheck1 = true;
Debug.Log("boxcheck1 = true");
}
if (boxcheck1 == true) {
GUI.Box(new Rect(10, 10, 800, 600), "");
}
}
}
Answer by Graham-Dunnett · May 28, 2013 at 01:20 PM
OnGUI() gets called multiple times per frame, once for each event that happens. In only one of these calls will boxcheck1 be true.
Your answer
Follow this Question
Related Questions
Target box displaying wrong 1 Answer
Draw Rectangle 0 Answers
Multiple button draws 1 Answer
How can I draw a box ingame? 2 Answers
Script only runs once? 2 Answers