Removing Int Value by another Int value

Hey Everyone!
I have been working on a money system for my game and i have a problem with one of my scripts. One of the scripts (Buying Script) grabs the ‘int’ from another script (Money Script) and subtracts it by another ‘int’.
The problem with it is that it doesn’t seem to subtract the value. Any help on this?

Buying Script:

private MoneyScript money1;
private int money2;
public int Cost;
public BuildingFollow ScriptA;

void Start()
{
money1 = GameObject.FindWithTag("MoneyCounter").GetComponent<MoneyScript>();
money2 = money1.money;
}

public void OnClick() {
if (money2 <= Cost)
        {
       Debug.Log("You don't have enough money");
      }
       else {
        money2 -= Cost;
          Debug.Log("RemovedMoney");
          ScriptA.AddObject();
          Debug.Log("AddedBUilding");
   }
}
}

Money Script:

public int money;
private Text MoneyCounter;

void Start()
{
MoneyCounter = GameObject.FindWithTag("MoneyCounter").GetComponent<Text>();
InvokeRepeating("MoneyAddMinute", 0.1f, 60f);
}

void Update() {
   MoneyCounter.text = money.ToString();
    }

    void MoneyAddMinute()
      {
         money += 500;
     }
}

Money is a value type, not a reference. When you do money2 = money1.money you grab the value of money at that moment. It’s not getting changed just because the value of money inside your money1 object gets changed. So that value probably contains 0 or whatever your default is, since you store the variable inside Start(). Vice versa, changing money2 does nothing to the money variable inside your money1 object.

Just replace money2 in your OnClick function with money1.money and it should work as you expect.

That said, you may wanna work on your naming sheme.

3 Likes