简体   繁体   中英

I am trying to make it so that my Unity game restarts after the game has ended

I don't know how to reload a scene so that the user can press a key and reset the game. Whenever I do it, the engine just crashes. The game is based on a cat chasing glasses around with a 120-second timer, and each of them has unique abilities. On collision, it should reload the scene. Is there any way that I can do this?

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

public class gamemanager : MonoBehaviour
{
    public GameObject catwin;
    public GameObject glasseswin;
    public timer timer;
    public Transform catpos;
    public Transform glassespos;
    public Vector3 catspawn;
    public Vector3 glassesspawn;
    public bool gameover = false;

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

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey("r"))
        {
            GameReset();
        }
    }

    public void CW()
    {
        catwin.SetActive(true);
        gameover = true;
        while (gameover)
        {
            if (Input.GetKey(KeyCode.R))
            {
                GameReset();
            }
        }
    }

    public void GW()
    {
        glasseswin.SetActive(true);
        if (Input.GetKey("r"))
        {
            GameReset();
        }
    }

    public void GameReset()
    {
        catwin.SetActive(false);
        glasseswin.SetActive(false);
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}

It crashes because the while loop inside the CW method is actually a while (true). When something calls this method it should wait until method is completed, but it'll never happen because of the loop. As a result, the program gets stuck while trying to execute infinitely many commands in one frame, so it has no other choice but to crash.

In order to fix it remove the loop from the method and check whether the key was pressed in Update. Something like this:

if (gameover && Input.GetKey("r")) 
    GameReset();

You can replace gameover with something else in order to include other conditions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM