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. Dismiss Notice

Field continues to increment inthe Update function.

Discussion in 'Scripting' started by magicscreen, Jun 3, 2015.

  1. magicscreen

    magicscreen

    Joined:
    May 19, 2015
    Posts:
    42
    I initially placed this issue into the wrong forum and was told to place it here.

    I am just getting started learning how to create games. I am using the Complete Unity 5 Developer course.

    I am assuming that this problem appears a lot and is frustrating to beginning gamers.

    I have a function that is being called from void Update which includes an update to a field.

    the variable myState is set by another function.

    These are the functions:

    Code (csharp):

    Code (csharp):
    1.  
    2. [LIST=1]
    3. [*]void Update () {
    4. [*]print (myState);
    5. [*]if (myState == States.piggyBank) {piggyBank ();}
    6. [*]}
    7. [/LIST]
    8.  
    Code (csharp):
    1.  
    2. [LIST=1]
    3. [*]void piggyBank (){
    4. [*]myMoney = myMoney + 5.00m;
    5. [*]text.text = "You added $5 from your Piggy Bank to your money to buy candy. \n\n" +
    6. [*]                 "You now have " + string.Format("{0:C}", myMoney) + " available to spend. \n\n" +
    7. [*]                 "Press R if you change your mind and/or want to return to Home. " +
    8. [*]                 "Press M to continue to the Store.";
    9. [*]if (Input.GetKeyDown(KeyCode.M))  {myState = States.money;}
    10. [*]else if (Input.GetKeyDown(KeyCode.R))  {myState = States.home;}
    11. [*]}
    12. [/LIST]
    13.  
    [Problem]
    myMoney = myMoney + 5.00m; keeps looping until I hit an M or an R key.

    I believe it is because I am in the Update mode and it keeps processing frame by frame.

    Is there any way to only set this instruction to only add the 5.00 once while this function is running?

    I tried to call the function from within another function bypassing the void Update function but then nothing happened.

    [/Problem]

    Thanks for any help given.

    magicscreen
     
  2. dterbeest

    dterbeest

    Joined:
    Mar 23, 2012
    Posts:
    389
    Update is called every frame. As long as myState equals states.piggybank the piggybank function will be called.
    You could try to set myState to something else in the piggybank function and put the input code directly in the update
     
  3. magicscreen

    magicscreen

    Joined:
    May 19, 2015
    Posts:
    42
    Thank you for your suggestion.

    It worked like a charm. You are the best.

    This is where I placed my code.

    Code (csharp):
    1.  
    2. if (Input.GetKeyDown(KeyCode.M)) {candyCost = 4.75m; myState = States.candyPrice;}
    3.  
    Thanks again.