Source file unity-csharp/arcade-classics/robotron-lite/Bullet.cs from the GDnD code examples. Download raw file

// GDnD wiki example
// Demonstrates: a directional bullet that kills an enemy on overlap and clears itself
// Related pages: [[overview-arcade-classics-as-learning-projects]], [[unity-collider2d-and-triggers]], [[object-pool-pattern]]
 
using UnityEngine;
 
// Plain Instantiate/Destroy bullet, fired along the aim vector. Twin-stick games
// spray a lot of these, so in a real build you would pool them — see
// [[object-pool-pattern]] (covered in step 4).
public class Bullet : MonoBehaviour
{
    [SerializeField] private float lifetime = 1.5f;
    [SerializeField] private float hitRadius = 0.15f;
 
    private Vector2 velocity;
    private LayerMask targetMask;
    private float age;
 
    public void Launch(Vector2 direction, float speed, LayerMask mask)
    {
        velocity = direction.normalized * speed;
        targetMask = mask;
    }
 
    private void Update()
    {
        transform.position += (Vector3)(velocity * Time.deltaTime);
        age += Time.deltaTime;
 
        Collider2D hit = Physics2D.OverlapCircle(transform.position, hitRadius, targetMask);
        if (hit != null)
        {
            hit.GetComponent<Enemy>()?.Hit();
            Destroy(gameObject);
            return;
        }
 
        if (age >= lifetime)
        {
            Destroy(gameObject);
        }
    }
}