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

// GDnD wiki example
// Demonstrates: a short-lived projectile that travels along a vector and triggers an asteroid split on hit
// Related pages: [[overview-arcade-classics-as-learning-projects]], [[unity-collider2d-and-triggers]], [[object-pool-pattern]]
 
using UnityEngine;
 
// A plain Instantiate/Destroy bullet. Step 4 already taught pooling; here the
// focus is spawning and splitting, so the bullet stays simple. For a real game
// you would pool these — see [[object-pool-pattern]].
public class Bullet : MonoBehaviour
{
    [SerializeField] private float lifetime = 1.2f;
    [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<Asteroid>()?.Hit();
            Destroy(gameObject);
            return;
        }
 
        if (age >= lifetime)
        {
            Destroy(gameObject);
        }
    }
}