Want to give player option to restart game w/ key press

Hello,

So after the player hits enter, confirming that the correct number has been guessed I would like a message to appear that says “Press Enter to Test My Skills Again!”. Then a second press of Enter would initiate a new game.

I can get the message to appear but the game just restarts without the need for an additional “Enter” input from the player. I believe the issue is that after the player presses Enter the first time, the next frame occurs and it starts looking for any input again as the void update() function starts over. I’m wondering how I can make the script pause after 1 key input of Enter, and wait for a second one before taking any further action? This is what I have so far, if anyone has any ideas I’d appreciate any feedback, Thank you.

void Start()
{
        StartGame();  
}

void StartGame()
{
    max = 1000;
    min = 1;
    guess = 500;

    Debug.Log("Welcome to Number Wizard Fellow Friend and Traveler.");
    Debug.Log("Please Choose a Number Between " + min + " and " + max + "." + " But Don't Tell Me What it is!");
    Debug.Log("Is Your Number is Higher or Lower Than " + guess + "?");
    Debug.Log("Press Up if Your Number is Higher Than " + guess + ".");
    Debug.Log("Press Down If your Numbers is Lower Than " + guess + ".");
    Debug.Log("Press Enter When I Have Correctly Guessed Your Number.");
    max = max + 1;
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.UpArrow))
    {
        Debug.Log("So, Your Number is Higher Than " + guess + "...");
        min = guess;
        NextGuess();
    }

    else if (Input.GetKeyDown(KeyCode.DownArrow))
    {
        Debug.Log("So, Your Number is Lower Than " + guess + "...");
        max = guess;
        NextGuess();
    }

    else if (Input.GetKeyDown(KeyCode.Return))
    {
        Debug.Log("So I Finally Got it! Your Number Was " + guess + "!");
        Debug.Log("Press Enter to Test My Skills Again.");
    
    if (Input.GetKeyDown(KeyCode.Return))
    
        StartGame();
    }
}
void NextGuess()
{
        guess = (max + min) / 2;
        Debug.Log("Is Your Number " + guess + "?");
}

}

Hi,

Your solution requires a bit more complex solution but if you are willing to learn something by reading, you’ll certainly be able to make your idea work. “Complex” does not mean “complicated”. It means that the solution is not just one line of code.

What you need are game states based on which you define what is supposed to get executed in Update. For example, when the player pressed “enter” the first time, the game is supposed to stop according to your idea. An idea is not an implementation, though. Unity does not know what “stop” means. For this reason, you need a “game stopped” state, a “playing” and “starting” state, or whatever you need. Does that make sense so far?

If so, take a look at this article about enums. Also read the example and try to apply it in your game. Instead of “Importance”, you define “GameState” in your NumberWizard code.

https://www.dotnetperls.com/enum

The first four paragraphs and the example are relevant for you, not the part as of “Enum advantages”.

Then you need if/else statements in the Update method. And you need to change the state depending on what is supposed to happen next.

Good luck! :slight_smile:

Thank you so much for the quick reply and information. I guess I’m getting a little ahead of myself as a complete beginner lol. I didn’t realize a seemingly simple task would have such a complex solution! I’m going to work with the article you sent me, and see if I can figure this out after work today. Thank you again!

In my opinion, this task should not be too difficult for you. Except for enums, which are very simple, you know everything you need. Forget about “a little ahead of myself” because you are progressing by constantly getting a little ahead of yourself. The best way to learn is to challenge oneself.

I think the difficult part is to find good names for the states.

If you get stuck, feel free to share your approach here and try to describe what you did so far, what your goal is and what doesn’t work as expected yet. I will probably be able to assist you a bit. :slight_smile:

I just gave it a real effort for like 2 hours lol but I have no clue how to do what I want based on that article. I can see what is being achieved in their example but I don’t understand how to inject it into my code. I tried so many things and my brain is complete mush at this point. I can’t even articulate what to ask so I am just moving on back to the videos.

If you would like to implement your idea, do the following: Define an enum with your desired game states. Check the example in the linked article. Then post your result here. That’s the first step of three or four. In my personal opinion, finding names for states is the most difficult part. At least for me, so finding names is your job. :wink:

And don’t be afraid from making mistakes. I’m also fine with a list of names for states. The names need to be one word without a space. Then I can show how to define the enum.

So I got a little further than that last night, I’m going to post the script so you can check it out. I put some notes in there to kind of help explain where I’m stuck. I really appreciate your time here so thank you again for all your effort and help thus far.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class NumberWizard : MonoBehaviour
{
    int max;
    int min;
    int guess;

    enum GameState
    {
        None,
        Active,
        Static,
        Restart
    }

    // Start is called before the first frame update
    void Start()
    {
        StartGame();
    }

    void StartGame()
    {
        max = 1000;
        min = 1;
        guess = 500;

        Debug.Log("Welcome to Number Wizard Fellow Friend and Traveler.");
        Debug.Log("Please Choose a Number Between " + min + " and " + max + "." + " But Don't Tell Me What it is!");
        Debug.Log("Is Your Number is Higher or Lower Than " + guess + "?");
        Debug.Log("Press Up if Your Number is Higher Than " + guess + ".");
        Debug.Log("Press Down If your Numbers is Lower Than " + guess + ".");
        Debug.Log("Press Enter When I Have Correctly Guessed Your Number.");
        max = max + 1;
    }

    static void Main()
    {
        GameState value = GameState.Active;
        GameState value = GameState.Static;
        GameState value = GameState.Restart;

        if (value == GameState.Active)
        {
            // I want the game to function as is, if the Active state is detected. And that would be when the user presses Up or Down
        }
        
        else if (value == GameState.Static)
        {
            // I don't know what to put here to make the game just wait for further input
        }

        else if (value == GameState.Restart)
        {
            // I think this is correct? lol I want the game to run this function when Restart is achieved. 
            void StartGame();
        }
    }

            // I'm not sure how to assign those enum states to the void Update below


    // Update is called once per frame
    void Update()
    {

        //  Is this necesarry I thought I would have to tell it to run that loop somehow


        static void Main();

        if (Input.GetKeyDown(KeyCode.UpArrow) )
        {
            Debug.Log("So, Your Number is Higher Than " + guess + "...");
            min = guess;
            NextGuess();
        }

        else if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            Debug.Log("So, Your Number is Lower Than " + guess + "...");
            max = guess;
            NextGuess();
        }

        else if (Input.GetKeyDown(KeyCode.Return))
        {
            Debug.Log("So I Finally Got it! Your Number Was " + guess + "!");
            Debug.Log("Press Enter to Test My Skills Again.");
        
        if (Input.GetKeyDown(KeyCode.Return))
        
            StartGame();
        }
    }
    void NextGuess()
    {
            guess = (max + min) / 2;
            Debug.Log("Is Your Number " + guess + "?");
    }
}

Well done so far. :slight_smile:

The GameState enum is defined correctly meaning it’s valid code. What you need is an instance variable which holds one of the enum values. You named your variable value, which is fine so far.

There are three problems which prevent your code from working:

  1. A compiler error because there are three variables with the same name declared within the same scope. That’s not possible in C#.
  2. You need only one variable because you want things to happen based on one state. If you had multiple factors such as state, score and health, which are supposed to depend on one another, you need multiple variables.
  3. If you declare a variable locally in a method, the variable and its value gets lost once the method is done executing its code. Since you need the value to persist during the lifetime of this NumberWizard instance, you declare the variable at instance level like your min, max and guess variables. Give it an initial value, ideally “Start”, which you have to add to your GameState list.

        else if (value == GameState.Restart)
        {
            // I think this is correct? lol I want the game to run this function when Restart is achieved. 
            void StartGame();
        }

That’s almost correct. Remove the void because you want to call the StartGame method, not declare a new one. There are more unintended method declarations in your code.

What is missing is to set the value variable to another GameState value because you want something else to happen when the Main method gets called.


What I would do is to move the code from Main() to Update() because the game state is supposed to make your program execute specific code blocks. At the moment, the if-conditions in Update aree getting checked each frame because there is nothing that prevents that from happening.

You could use the Update method to define which methods are supposed to get executed. And you may define more methods depending on your needs.

Nested ifs are possible, too. Or two conditions inside the parentheses. && means “and”, || means “or”.

For example:

else if (value == GameState.Restart && Input.GetKeyDown(KeyCode.Return))
{
}

Start with fixing the compiler errors. Then declare your instance variable, name it state instead of value because that’s a more meaningful name in my opinion. Move the if-blocks from Main to Update and wrap the code inside the Update method in the respective “state” if-blocks. Last but not least, set the value of state to the correct GameState value during runtime depending on what is supposed to happen.

You already implemented everything you need, apart from fixing the compiler errors, all you have to do is to rearrange your code a bit.

1 Like

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

Privacy & Terms