C# Galaga类项目:限制Hierarchy中投射物Prefab克隆体数量的问题
修复方案
核心问题
你的代码存在两个逻辑错误:
- 执行顺序完全颠倒:先实例化子弹再判断数量上限,相当于已经生成了超量子弹后才销毁,属于无效判断
- 计数没有同步子弹销毁状态:子弹超时/碰撞销毁时没有对
maxBullets做减法,计数会只增不减,后续永远会触发超量判断
修改步骤
1. 修正playerController逻辑
把判断逻辑移到实例化之前,同时优化变量命名方便后续维护:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class playerController : MonoBehaviour { public float moveSpeed = 1.0f; public playerProjectile projectile; public Transform launchOffset; public int currentBulletCount = 0; // 直接配置上限,后续改规则不用动逻辑 public int maxAllowedBullets = 2; public Rigidbody2D player; void Start() { player = this.GetComponent<Rigidbody2D>(); } void Update() { MovePlayer(); PlayerShoot(); } public void MovePlayer() { player.velocity = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")) * moveSpeed; } public void PlayerShoot() { if (Input.GetKeyDown(KeyCode.Z)) { // 先判断数量,超上限直接不生成 if (currentBulletCount >= maxAllowedBullets) { return; } playerProjectile newProjectile = Instantiate(projectile, launchOffset.position, launchOffset.rotation); // 给子弹绑定当前控制器,方便销毁时回调计数 newProjectile.owner = this; currentBulletCount++; } } }
2. 补充投射物脚本的计数回调
在你现有的playerProjectile脚本中,所有销毁子弹的逻辑前,补充计数减少的代码,示例完整代码参考:
using UnityEngine; public class playerProjectile : MonoBehaviour { // 用于绑定所属的玩家控制器 public playerController owner; public float lifeTime = 2f; public float shootSpeed = 10f; void Start() { GetComponent<Rigidbody2D>().velocity = Vector2.up * shootSpeed; // 超时自动销毁 Invoke(nameof(DestroyProjectile), lifeTime); } void OnCollisionEnter2D(Collision2D other) { // 碰撞销毁逻辑 DestroyProjectile(); } void DestroyProjectile() { // 销毁前先减少玩家的子弹计数 if (owner != null) { owner.currentBulletCount--; } Destroy(gameObject); } }
注意事项
- 所有触发子弹销毁的分支(比如碰到敌机、碰到屏幕边界、切场景清理)都要走
DestroyProjectile方法,避免计数不同步 - 不需要额外做超量子弹的销毁逻辑,前置判断已经从根源限制了生成数量,性能开销更低
内容的提问来源于stack exchange,提问作者MsRiaCayde
相关产品推荐
相关产品推荐

