using UnityEngine; public class Bullet : MonoBehaviour { public float speed = 10f; private Vector3 direction; private bool initialized; public BulletStates bulletState; public float lifeTime = 10f; public GameObject nearMissEffectPrefab; public void Init(Vector3 targetPos) { direction = (targetPos - transform.position).normalized; initialized = true; } void Update() { // ❌ prevent running before Init if (!initialized) return; // ⏱ lifetime countdown lifeTime -= Time.deltaTime; if (lifeTime <= 0f) { Destroy(gameObject); return; } // Move transform.position += direction * speed * Time.deltaTime; // Rotate to face movement Vector2 dir = direction; float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.Euler(0, 0, angle); } public void Reverse() { direction = -direction; } public void OnCollisionEnter2D(Collision2D collision) { if (!collision.collider.CompareTag("Bullet")) return; if (bulletState != BulletStates.reversed) return; Destroy(collision.gameObject); Destroy(gameObject); } private void OnDestroy() { Instantiate(nearMissEffectPrefab, this.gameObject.transform.position, Quaternion.identity); } } public enum BulletStates { active, inNearMissZone, inPointZone, markForDeletion, reversed, inactive }