我不知道为什么,但是当我在Unity中按Play玩游戏时,一切正常。最后,当我击败老板时,出现了一个带有按钮的面板,该按钮可以转到主菜单场景。并且在主菜单中,您显然有一个“播放”按钮,该按钮可以引导到关卡场景,当您单击它再次播放时,我会得到所有以下错误:
我认为该类不再找到Boss(游戏对象在被击败后被销毁了)?但是我不明白,因为我认为在单击“主菜单”中的“播放”按钮后,每次“播放”都会重新启动场景,并且老板仍然处于层次结构中。
这是脚本:
public class HUDController : MonoBehaviour {
//Public variables
public Image[] lives;
public GameObject gameOverPanel;
public GameObject winPanel;
public Image oxBar;
public float oxSpeed;
public Text foodPoints;
public Slider bossHealthBar;
public GameObject fireworks;
[HideInInspector]
public bool stop;
[HideInInspector]
public float currentOx = 100f;
[HideInInspector]
public float maxOx = 100f;
//Private variables
private PlayerController player;
private BossController boss;
private float timer = 0;
void Start()
{
player = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerController> ();
boss = GameObject.FindGameObjectWithTag ("Boss").GetComponent<BossController> ();
gameOverPanel.SetActive (false);
winPanel.SetActive (false);
stop = false;
fireworks.gameObject.SetActive (false);
bossHealthBar.maxValue = boss.health;
bossHealthBar.gameObject.SetActive (false);
}
void Update () {
DisplayLives ();
DisplayFood ();
if (boss.startFire) {
bossHealthBar.gameObject.SetActive (true);
DisplayBossHealth ();
}
if (boss.health <= 0) {
timer += Time.deltaTime;
bossHealthBar.gameObject.SetActive (false);
if (timer > 1f) {
fireworks.gameObject.SetActive (true);
winPanel.SetActive (true);
}
}
float ratio = currentOx / maxOx;
oxBar.rectTransform.localScale = new Vector3 (ratio, 1f, 1f);
DecreaseOxygen ();
if (player.lives <= 0 || currentOx <= 0) {
stop = true;
currentOx = 0f;
gameOverPanel.SetActive (true);
}
}
//Shows lives available
void DisplayLives(){
for (int i = 0; i < lives.Length; i++)
{
if (i < player.lives) {
lives [i].enabled = true;
} else {
lives [i].enabled = false;
}
}
}
void DisplayFood(){
foodPoints.text = player.foodPoints.ToString();
}
void DecreaseOxygen(){
if (boss.bossDefeated) {
currentOx -= oxSpeed * Time.deltaTime;
}
}
void DisplayBossHealth(){
bossHealthBar.value = boss.health;
}
}
这是第41行:
bossHealthBar.maxValue = boss.health;
这是第50行:
if (boss.startFire) {
也许不是因为老板吗?如果您需要我向您显示更多代码,请告诉我!请帮忙。
编辑:我添加了整个脚本。该脚本附加到我的Hud(带有UI的Canvas)上,并且该脚本需要访问附加到Boss(BossController)的脚本,以访问UI的某些变量(运行状况,某些布尔值)。 似乎场景无法正确加载对象,因为如果从主菜单启动游戏,则会遇到相同的错误。但是,如果我只是在关卡场景中在Unity中按Play,它就可以正常工作。
所以我调试了游戏,并且不会分配BossController,它保持为空:
我不知道为什么。标签正确,并且老板仍在层次结构中。而且玩家得到了完美的分配,所以我不知道有什么不同。