You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity 2D游戏中如何用C#加载死亡/游戏结束场景?

Unity2D 生命耗尽加载死亡场景问题修复

你的代码存在几个关键问题导致死亡场景无法触发:

  1. Deathscene() 是私有方法且从未被调用,永远不会执行
  2. SceneManager.LoadScene(Bob) 中的Bob是未定义变量,场景名必须是字符串类型
  3. 没有在生命减少的时机触发死亡检测

修改方案:

1. 调整SceneLoader脚本

添加死亡场景名称变量,将死亡场景加载方法改为公共方法以便外部调用:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneLoader : MonoBehaviour
{
    public string sceneName;
    public GameManager GM;
    public string deathSceneName; // 死亡场景名称,在Inspector面板设置

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Player")
        {
            SceneManager.LoadScene(sceneName);
        }
    }

    // 供外部调用的死亡场景加载方法
    public void LoadDeathScene()
    {
        if (GM.LifeTotal <= 0)
        {
            SceneManager.LoadScene(deathSceneName);
        }
    }
}

2. 修改GameManager脚本

在扣血后立即检查生命是否耗尽,调用死亡场景加载:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    public int PotionsCollected = 0;
    public int LifeTotal = 3;

    public Text PotionsOutput;
    public Text LifeOutput;
    public SceneLoader sceneLoader; // 在Inspector面板拖入SceneLoader对象

    void Update()
    {
        PotionsOutput.text = "Potions: " + PotionsCollected;
        LifeOutput.text = "Life: " + LifeTotal;
    }

    public void CollectPotion()
    {
        PotionsCollected++;
    }

    public void UsePotion()
    {
        PotionsCollected--;
    }

    public void LoseLife()
    {
        LifeTotal--;
        // 生命耗尽时触发死亡场景
        if (LifeTotal <= 0)
        {
            sceneLoader.LoadDeathScene();
        }
    }
}

最后配置步骤:

  • 在Unity编辑器中,给SceneLoader组件的deathSceneName填入你的死亡场景名称(比如"GameOver")
  • 将SceneLoader对象拖入GameManager组件的sceneLoader变量中
  • 确保死亡场景已添加到Build Settings的Scenes In Build列表(File -> Build Settings,拖拽场景到列表)

内容的提问来源于stack exchange,提问作者Molly Peate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 15:40:49