Having trouble on understanding how Update() function works

Hello,

I have been enjoying the lectures a lot. I just finished through Number Console and came up with ideas for adding something to the game too. First of all, I wanted to add the option of making Instructions to the game available to the user while playing the game. Next, I wanted user to press any key to start the game. And also, the option to quit the game while playing the game or after winning.
I have managed to implement these options so far with the help of other threads or topics here; which gave me an understanding of use of enums. It was really fun trying to implement all these.
But now, I am having trouble in different scenario. In the beginning, when prompted to press any key to start the game. If I press the (up or down) key, it would skip the first attempt to ask user if it was higher or lower. Here is an example,

Press any key to start
(up arrow pressed)

Is it higher or lower than 500?
Damn! It was higher! ->>>> I didnt get to press an up arrow key here, instead it accepted the up key I pressed for “press any key to start”
Is it higher or lower than 750?

Similarly, after a correct guess is made, I wanted user to press Enter to restart or space to quit
however, when user presses Enter, it would take the same key as response to another.

Press Enter to play again or space to quit
“presses Enter”
" Is it higher or lower than 500?"
" Told ya I am a genius" —> Took Enter as response to correct guess

After all this, I am beginning to question if I am using or understanding the Update() function in a wrong way?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Debug = UnityEngine.Debug;

public class NumberWizard : MonoBehaviour
{
    int max = 1000;
    int min = 1;
    int guess = 500;

    enum GameState
    {
        Active,
        Offlyn,
        Restart,
        Pause
    }

    GameState state = GameState.Offlyn;

    // Start is called before the first frame update
    void Start()
    {
        Instructions();
        Begin();
    }
    void Instructions()
    {
        Debug.Log("Namaste! Welcome to Number Wizard.");
        Debug.Log("Pick any number. Dont tell me what it is....");
        Debug.Log("Highest number you can pick is " + max);
        Debug.Log("Lowest number you can pick is " + min);
        Debug.Log("Tell me if your number is less than or greater than my guess");
        Debug.Log("Push Up = Higher, Push Down = Lower, Push Enter = Correct, Push Space = Quit");
        Debug.Log("Push Ctrl to pause the game and view Instructions");

    }

    void Begin()
    {
        state = GameState.Pause;
        max = 1001;
        min = 1;
        guess = 500;
        Debug.Log("~~~~ Number Wizardry of Hogwarts ~~~~~ ");
        //Debug.Log("Is it higher or lower than..." + guess + " ?");
        Debug.Log("Press any Key to Start");
    }

    void NextGuess()
    {
        guess = (max + min) / 2;
        // guess = Random.Range(min, max);
        Debug.Log("Is it higher or lower than..." + guess + " ?");
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space) && state != GameState.Offlyn)
        {
            Debug.Log(">__< See you!");
            state = GameState.Offlyn;
        }
        else if(state == GameState.Restart)
        {
            if (Input.GetKeyDown(KeyCode.Return))
            {
                Begin();
            }
        }
        else if (state == GameState.Pause)
        {
           if (Input.anyKeyDown)
          {
              state = GameState.Active;
              Debug.Log("Is it higher or lower than..." + guess + " ?");
            }

        }
        else if (state == GameState.Active)
        {
            if (min >= 1000 || max <= 1)
            {
                Debug.Log("Such a bully! You chose number outside the range :(");
                Debug.Log("Lets Start the Game again! But First Read The Instructions!");
                Instructions();
                Begin();
            }
            else
            {
                if (Input.GetKeyDown(KeyCode.UpArrow))
                {
                    Debug.Log(" Damn, it was higher!");
                    min = guess;
                    NextGuess();
                }
                else if (Input.GetKeyDown(KeyCode.DownArrow))
                {
                    Debug.Log("Damn, it was lower!");
                    max = guess;
                    NextGuess();
                }
                else if (Input.GetKeyDown(KeyCode.Return))
                {
                    state = GameState.Restart;
                    Debug.Log("Told ya! I am a Mad Genius!");
                    Debug.Log("Wanna Start Again? Press Enter to play or Space to Quit");
                }
                else if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl))
                {
                    state = GameState.Pause;
                    Instructions();
                    Debug.Log("Press any Key to Continue The Game");
                }
            }
        }

    }
}
1 Like

Hi Shawnfrost,

Welcome to our community! :slight_smile:

Good job on challenging yourself. I skimmed your code, and your Update method looks fine. You obviously understood the idea behind the enum states. The only flaw I see is the missing else because state cannot be GameState.Offlyn and GameState.Restart simultaneously. With an else, your code would be a bit more performant. I would also put the state condition first because when the space key was pressed down but state is not GameState.Offlyn, the program would have to check two conditions even though it would have been sufficient to check only one.

I suspect this might also be the reason why the program appears to skip a step because all if-conditions get checked. Since state gets set to GameState.Active when you press “any key”, the next if-condition gets evaluated to true as well.

Does that make sense?

Hi Nina,

Thank you very much. I have been enjoying the course so far. I only get time to go through the course weekends only but its been really a wonderful experience to learn to code and make some innovations.

Hmm, I think i got the point you are establishing. Since the state variable would change its value after the if statement, the missing else would make it easier to perform the way I want it to. I was learning to code in C programming and Update() function looked like a while loop or recursive function to me at first. That’s why it took a lot of hit and trials to make it the way I wanted to at first, lol. But it is getting more interesting the more I learn.

I edited the code with your help and it works great! I still am little confused about the frames. Everything worked great except for one thing. I wanted to print a statement "Is it higher or lower… than last guess after the user presses any key to continue the game but it apparently took the input ctrl key as any key to continue the game. So, I looked over the docs and switched Input.anyKey to Input.anykeyDown and it worked smooth. I dont know how it made it right though.

Good job on making your idea work. :slight_smile:

The Update method can be regarded as a loop because it gets called once per frame. Scroll down to the flowchart on the following webpage:

https://docs.unity3d.com/Manual/ExecutionOrder.html

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms