Unity游戏销毁全部平台后加载下一关的实现问题求助
问题分析与解决方案
第一种方法的问题根源
每个子弹预制体实例都拥有独立的DestroyedPlatforms变量,单颗子弹摧毁一个平台后,该变量仅在当前子弹实例中计数为1,其他子弹的计数仍为0,永远无法累计到3。
第二种方法的问题根源
- 方法名错误:Unity的帧更新方法是大写开头的
Update(),你写的小写update()不会被Unity自动调用,代码根本没执行。 - 判断逻辑错误:
GameObject.FindGameObjectsWithTag("platform")永远不会返回null,当没有平台时它会返回一个长度为0的空数组,所以platform == null的判断永远不成立。
推荐解决方案
方案1:修复GameManager脚本(推荐)
修改后的代码可在游戏开始时统计总平台数,或每帧检查剩余平台数,触发下一关逻辑:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { private int totalPlatforms; void Start() { // 游戏启动时获取初始平台总数 totalPlatforms = GameObject.FindGameObjectsWithTag("platform").Length; } void Update() { // 每帧检查剩余平台数量 int remaining = GameObject.FindGameObjectsWithTag("platform").Length; if (remaining == 0) { Debug.Log("load next level"); // 后续替换为实际加载关卡代码: // SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } } // 可选:通过事件通知的方式计数,避免每帧查找对象 public void NotifyPlatformDestroyed() { totalPlatforms--; if (totalPlatforms <= 0) { Debug.Log("load next level"); } } }
方案2:修改子弹脚本配合GameManager
如果想用子弹触发计数,修改子弹脚本,让它调用GameManager的计数方法:
public void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("platform")) { Destroy(other.gameObject); // 查找场景中的GameManager实例 GameManager gm = FindObjectOfType<GameManager>(); if (gm != null) { gm.NotifyPlatformDestroyed(); } Debug.Log("Platform destroyed"); } }
注意事项
- 将GameManager脚本挂载到场景中的一个空物体上,确保场景中只有一个GameManager实例。
- 确认所有平台的Tag设置为
platform(Unity的Tag大小写敏感)。
内容的提问来源于stack exchange,提问作者jlaw
相关产品推荐
相关产品推荐

