How to resume game after pressing back in menu

两盒软妹~` 提交于 2021-02-05 05:39:45

问题


Hey I am trying to make a pause menu in my game. When escape is pressed pause game go to menu, but now I want to be able to press back in menu and resume my game. So far I can only pause game and cant press back. Also if i press Play in menu it starts at my tutorial scene and not the current scene. Is there a smart way to do this? Without resetting my game.

`using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class MenuScript : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.Escape))
        {
            if (Time.timeScale == 0)
            {
                Time.timeScale = 1;
            }
            else
            {
                Time.timeScale = 0;
            }
            SceneManager.LoadScene("Menu");




        }

    }
}`

回答1:


I get that this isn't straightforward problem since you seem new to Unity.

You got the idea correctly, changing the time scale will freeze all agents on the scene. HOWEVER, if you load a new scene you'll need to reload the game scene - losing any data you had (and that is not what you want). My advice is creating an overlay element (UI) on the game scene and just show/hide it. There are multiple tutorials online use this as an starting point. Let me know if you require more help.

code sample

// Update is called once per frame
void Update()
{
  if (Input.GetKey(KeyCode.Escape))
  {
    if (Time.timeScale == 0)
    {
        Time.timeScale = 1;
        pauseMenu.gameObject.setActive(true);
    }
    else
    {
        Time.timeScale = 0;
        pauseMenu.gameObject.setActive(false);
     }
  }
}

You will need a reference to the pauseMenu game object attached on this script using the Unity editor.



来源:https://stackoverflow.com/questions/53432787/how-to-resume-game-after-pressing-back-in-menu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!