Unity子弹GameObject达到X=10时未销毁,逻辑问题求助
子弹X位置达到10时未销毁的问题修复
问题根源
- Target为空时跳过销毁逻辑:
FixedUpdate里的if(!target) return;会导致当目标被销毁或未设置时,后续的位置判断代码完全不执行,子弹永远不会被销毁。 - 单向判断局限性:如果子弹是向左飞行(目标在当前位置左侧),
transform.position.x > 10的条件永远无法满足,子弹会一直飞下去。 - 物理帧跳过问题:
FixedUpdate的执行间隔可能导致子弹位置直接越过10,错过判断时机。
修复方案
方案1:调整逻辑顺序,覆盖无Target场景
把位置判断移到target检查的外面,确保无论有没有目标都执行销毁逻辑,同时改用绝对值判断覆盖双向飞行场景:
private void FixedUpdate(){ if(target){ Vector2 direction = (target.position - transform.position).normalized; rb.linearVelocity= direction * bulletSpeed; } // 无论是否有目标,都检查X轴边界 if(Mathf.Abs(transform.position.x) > 10){ Destroy(gameObject); } }
方案2:使用屏幕可见性判断(更通用)
利用Unity的OnBecameInvisible()方法,当子弹离开相机视野时自动销毁,无需硬编码位置:
private void FixedUpdate(){ if(!target){ return; } Vector2 direction = (target.position - transform.position).normalized; rb.linearVelocity= direction * bulletSpeed; } void OnBecameInvisible(){ Destroy(gameObject); } void OnCollisionEnter2D(Collision2D other){ Health health = other.gameObject.GetComponent<Health>(); if(health){ // 避免空引用报错 health.TakeDamage(dmg); } Destroy(gameObject); }
额外优化:碰撞检测空引用防护
原OnCollisionEnter2D里直接调用GetComponent<Health>().TakeDamage会在目标没有Health组件时报错,建议增加空判断。
内容的提问来源于stack exchange,提问作者azaessa
相关产品推荐
相关产品推荐

