Debug Log loop when my If is true..

Here’s the deal guys. I’m trying to create a simple thing. When I click on a button I want to check if the totalMoney that I have is more or less than 10. If it’s more than 10 then in the console should appear “You’ve Build A House” and that is working perfectly fine! But when the money is less than 10 and I click on the GUI Button the console just goes CRAZY and doesn’t stop looping and saying - NO MONEY NO MONEY NO MONEY… Why is it doing this? I know the OnGUI function is called per frame but shouldn’t it stops once the console return me that there is no money? I don’t get it :(. Here is the code:

using UnityEngine;
using System.Collections;

public class menu : MonoBehaviour {

public int left;
public int top1;
public int top2;
public int top3;

private bool house;

public int totalMoney;
public GUIText moneyText;

void Start()
{
	house = false;
	moneyText.text = "Total Cash: " + totalMoney;
}

void Update()
{

}

void OnGUI () 
{
	GUI.Box(new Rect(40,50,200,160), "Build");

	if(GUI.Button(new Rect(left,top1,120,30),"House") && totalMoney >= 10)
	{
		totalMoney = totalMoney - 10;
		moneyText.text = "Total Cash: " + totalMoney;
		Debug.Log("You've build a house!");
	}
	
	else if (GUI.Button(new Rect(left,top1,120,30),"House") || totalMoney < 10)
	{
		Debug.Log("No money!");
	}
	
	GUI.Button(new Rect(left,top2,120,30),"Aparment");
	GUI.Button(new Rect(left,top3,120,30),"District");

}

}

I’m trying to build a simple town “game” and I want when I click from the menu on House to instantiate a house prefab somewhere on the map and subtract the cost of that house from my money, if I don’t have the money then a pop-out window should appear saying that I don’t have money. Simple as that… and the houses or apartments or districts should give me [n] money per second… this is the first step and I’m already getting confused :frowning: help please!!!

An immediate fix is to change the logical or ‘||’ to an and ‘&&’ on line 34. But in reality is you have unnecessary code duplication. Structure your code like this instead:

if(GUI.Button(new Rect(left,top1,120,30),"House")) {
    if (totalMoney >= 10) {
       totalMoney = totalMoney - 10;
       moneyText.text = "Total Cash: " + totalMoney;
       Debug.Log("You've build a house!");
   }
   else {
     Debug.Log("No Money!");
   }
}