因此,我制作了这个测试GUI,当敌人的聚光灯到达您时,该游戏显示了游戏画面。但是当它发生时,Unity崩溃并注意到了错误
StackOverflowException: The requested operation caused a stack overflow.
这是我崩溃的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameUI : MonoBehaviour {
public GameObject gameLoseUI;
// public GameObject playerDiedUI;
//public GameObject noEnergyUI;
bool gameIsOver;
// Use this for initialization
void Start () {
Guard.OnGuardHasSpottedPlayer += ShowGameLoseUI;
}
// Update is called once per frame
void Update () {
/*if (gameIsOver)
{if (Input.GetKeyDown(KeyCode.Space))
{
SceneManager.LoadScene(0);
}
}*/
}
void ShowGameLoseUI()
{
OnGameOver(gameLoseUI);
}
void OnGameOver(GameObject gameoverUI)
{
gameLoseUI.SetActive(true);
gameIsOver = true;
Guard.OnGuardHasSpottedPlayer += ShowGameLoseUI;
}
}
我认为该错误可能在void Update内,但即使带有此注释的代码段,Unity仍然会崩溃。我该如何解决这个问题?
答案 0 :(得分:0)
如评论中所指出的,您在GameOver上无限订阅Guard.OnGuardHasSpottedPlayer
,这会导致异常。
将+=
更改为-=
void OnGameOver(GameObject gameoverUI)
{
gameLoseUI.SetActive(true);
gameIsOver = true;
Guard.OnGuardHasSpottedPlayer -= ShowGameLoseUI;
}