Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

[SOLVED] How to change the global variable in a script

Discussion in 'Scripting' started by bleszerd, Jun 21, 2020.

  1. bleszerd

    bleszerd

    Joined:
    Sep 3, 2019
    Posts:
    2
    I'm trying to change a variable in the "GameValues" script, but always what I call GameValues.value again it returns 0, but WHY???

    GameValues script:
    Code (CSharp):
    1.     private static int gameMoney;
    2.     private void Start()
    3.     {
    4.         gameMoney = 0;
    5.     }
    6.     public static void setGameMoney(int money)
    7.     {
    8.         gameMoney = money;
    9.     }
    10.  
    11.     public static int getGameMoney()
    12.     {
    13.         return gameMoney;
    14.     }
    ClickTriggerPlus10:

    Code (CSharp):
    1.     private void OnMouseDown()
    2.     {
    3.         GameValues.setGameMoney(GameValues.getGameMoney() + 10);
    4.     }
    ClickTriggerMinus10:

    Code (CSharp):
    1.     private void OnMouseDown()
    2.     {
    3.         GameValues.setGameMoney(GameValues.getGameMoney() - 10);
    4.     }


    I expected the getGameMoney function to return 40 after clicking 4x on the object with the ClickTriggerPlus10 script and 30 after clicking 1x on the ClickTriggerMinus10 script
     
    Last edited: Jun 21, 2020
  2. bleszerd

    bleszerd

    Joined:
    Sep 3, 2019
    Posts:
    2
    It was just a math error, the correct thing would be to add -10, contrary to what I had done previously :oops:

    ClickTriggerMinus10:

    Code (CSharp):
    1.     private void OnMouseDown()
    2.     {
    3.         GameValues.setGameMoney(GameValues.getGameMoney() + -10);
    4.     }