Unity如何激活实例化子弹的Projectile组件而不触发原始子弹?
问题修复方案
问题核心
开枪时误激活了原始子弹的Projectile组件,而非仅激活实例化后的子弹。原因是Shoot()方法中直接操作了bulletFinder.selectedBullet(原始子弹对象),而非Instantiate返回的实例对象。
预期流程回顾
- BulletMaker收集材料提升子弹属性,生成带禁用状态Projectile组件的子弹
- BulletFinder通过碰撞检测选中该子弹
- Gun实例化子弹并仅激活实例的Projectile组件
修复步骤
- 在
Gun的Shoot()方法中,保存Instantiate返回的实例对象,仅对该实例启用Projectile组件 - 移除
Projectile脚本中冗余的active变量,直接利用组件的enabled状态控制逻辑(组件禁用时Update不会执行,无需额外判断)
修改后的代码
Gun.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Gun : MonoBehaviour { public Transform muzzle; public int magazineSize; public int bulletsInMag; public float reloadTime = 3; bool reloading = false; BulletFinder bulletFinder; void Start() { bulletFinder = GameObject.Find("Bullet Holder").GetComponent<BulletFinder>(); } void Update() { if (bulletFinder.selectedBullet != null) { if (Input.GetKeyDown(KeyCode.Mouse0) && bulletsInMag > 0) { Shoot(); } else if (Input.GetKeyDown(KeyCode.Mouse0) && bulletsInMag <= 0 && !reloading) { Reload(); } } } private void Shoot() { if (bulletFinder.selectedBullet != null) { // 保存实例化后的子弹对象 GameObject instantiatedBullet = Instantiate(bulletFinder.selectedBullet, muzzle.position, muzzle.rotation); // 仅激活实例子弹的Projectile组件 instantiatedBullet.GetComponent<Projectile>().enabled = true; bulletsInMag--; } } private void Reload() { reloading = true; StartCoroutine(ReloadTime()); } IEnumerator ReloadTime() { yield return new WaitForSeconds(reloadTime); bulletsInMag = magazineSize; reloading = false; } }
Projectile.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Projectile : MonoBehaviour { public float damage; public float speed; private Rigidbody projectile; void Start() { projectile = GetComponent<Rigidbody>(); } void Update() { // 组件启用时才会执行Update,无需额外判断active if (projectile != null) { projectile.AddForce(transform.forward * Time.deltaTime * speed, ForceMode.Impulse); } } private void OnCollisionEnter(Collision collision) { Destroy(gameObject); } }
内容的提问来源于stack exchange,提问作者Big Glasses
相关产品推荐
相关产品推荐

