Search Unity

Adding restart option to 2D game

Discussion in 'Scripting' started by p1902s, Aug 21, 2018.

  1. p1902s

    p1902s

    Joined:
    Aug 14, 2018
    Posts:
    2
    Hi all,

    I've made myself a 2D game and currently am just simply running and stopping through Unity's play feature.

    I'd like to add a command where a keyboard button (R for example) can be pressed to restart/reset the game once the player has finished/failed.

    I've searched around and most things are talking about adding an actual button to the scene, which I don't wish to do. I would simply like to have a key command which restarts the game for the player.

    Some help in coding this into the game would be well appreciated. :)
     
  2. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    There are many ways to do this. You can take a look here to see how to detect a key up event.

    Once you have detected the key being released, restart the level in whatever way makes sense. But a standard game sequence will take you to some sort of game over, high score or main menu screen.

    These othere screens can be in other scenes. So loading a scene will start it afresh meaning you won't need to keep stopping and restarting the game.

    Does that help?
     
  3. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    Just to add to the previous comment, in the Editor you could add a new scene (called maybe GameOver). It could simply have an image saying "Game Over, press 'R' to replay".

    In the game scene you could detect when the game ends (for example, when the player dies) and then use LoadScene to load the GameOver scene. In that scene, detect the key up event (see previous comment) and then load the game scene again.