[英]I am trying to make an FPS soccer game using Unity, but my script isn't working
[英]I am trying to make it so that my Unity game restarts after the game has ended
我不知道如何重新加载场景,以便用户可以按键并重置游戏。 每当我这样做时,引擎就会崩溃。 游戏是基于一只猫追逐眼镜,有一个 120 秒的计时器,每个人都有独特的能力。 碰撞时,它应该重新加载场景。 有什么办法可以做到这一点吗?
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);
}
}
它崩溃是因为 CW 方法中的 while 循环实际上是一个 while (true)。 当有东西调用这个方法时,它应该等到方法完成,但由于循环,它永远不会发生。 结果,程序在试图在一帧中执行无限多的命令时卡住了,所以它别无选择,只能崩溃。
为了修复它,从方法中删除循环并检查是否在更新中按下了键。 像这样的东西:
if (gameover && Input.GetKey("r"))
GameReset();
您可以用其他东西替换gameover
以包含其他条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.