[英]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.
游戏是基于一只猫追逐眼镜,有一个 120 秒的计时器,每个人都有独特的能力。 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).它崩溃是因为 CW 方法中的 while 循环实际上是一个 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您可以用其他东西替换
gameover
以包含其他条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.