Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Int Value not being calculated correctly?

Discussion in 'Scripting' started by xrolliox, Feb 7, 2017.

  1. xrolliox

    xrolliox

    Joined:
    May 5, 2016
    Posts:
    55
    Hi, so I'm trying to create an in-game economy, and I've created two scripts that will add and subtract money.

    The money is added (with a value of 1000) on the left mouse click, and money is subtracted (with a value of 1000) with the right mouse button. Except when I click it will sometimes add or subtract 1000, 2000 or 3000 even though there is only one mouse press.
    Script one
    public void addMoney(int moneyToAdd)
    {
    money += moneyToAdd;
    }
    public void subtractMoney(int moneyToSubtract)
    {
    if (money - moneyToSubtract < -15000)
    Debug.Log("Not enough money");
    else
    {
    money -= moneyToSubtract;

    Script two (references script one)
    void Update () {
    if (Input.GetButton("Fire1"))
    {
    cam.GetComponent<Economy>().addMoney(1000);
    }
    if (Input.GetButton("Fire2"))
    {
    cam.GetComponent<Economy>().subtractMoney(1000);
    }
    }
     
  2. CrymX

    CrymX

    Joined:
    Feb 16, 2015
    Posts:
    179
    Use code tags, and what's your problem ?
     
  3. pk_Holzbaum

    pk_Holzbaum

    Joined:
    Jul 26, 2012
    Posts:
    85
    Change Input.GetButton to Input.GetButtonDown and that should solve your problem.
    GetButtonDown is only called once and GetButton is called many times, while you keep the button pressed.
     
  4. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    Code (CSharp):
    1. Input.GetButton
    Gets called ones per frame, and will return true as long as the button is pressed. Change that to
    Code (CSharp):
    1. Input.GetButtonDown
    2. // or
    3. Input.GetButtonUp
    and your problem will go away.

    Also, next time please use Code Tags when posting code.
     
  5. xrolliox

    xrolliox

    Joined:
    May 5, 2016
    Posts:
    55
    I had that code in originally (GetComponentUp/Down) and that had the same issue.