- Home /
Button on click needs to wait
Hi,
I'm trying to make an GUI system, and when you press on a button, a "building" mode activates and when you then click on the terrain you build the selected thing
but the problem is, when you click the button and behind that is the terrain it builds the object right away.
so in Images, the following works just fine, I click the button, and then on a second click on the terrain it builds the object:
but when the menu comes in front of the terrain when I click it builds the object right when I click:
The following code is used for that:
if (_BuildSelected != BuildingType.NN) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetMouseButtonUp(0) == true) {
switch (_BuildSelected) {
case BuildingType.House:
if (Physics.Raycast(ray, out hit))
CreateHouse(hit.point);
break;
default:
break;
}
}
}
and the button just sets the _BuildSelected to BuildingType.House, anyone got any ideas how to fix this?
Answer by Julien-Lynge · Jan 10, 2013 at 07:16 PM
I'm guessing the code you posted happens in OnGUI. One thing to note is that OnGUI can be called multiple times per frame, and Input.GetMouseButtonUp() will be true every time it's called.
There are a couple ways you can potentially solve this:
You could try moving your code to Update. However, I'm not sure about whether update is called before or after OnGUI, so this may not help.
When you click on the button, you could record the current frame in a variable. Then, in your code, check for a mouse up and that the current frame (Time.elapsedFrames) doesn't match the frame you recorded.
You could also use a Coroutine and yield to wait a frame before setting _buildSelected.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
GUI Button problem 0 Answers
Simulate a mouse Click? 2 Answers
How do I make a UI button to click a key? 1 Answer
Unity UI Button not working 1 Answer