[英]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.