Menu
CoddyTech

Bullets That Hit

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 56 of 71.

challenge icon

Challenge

Medium

Write the bullet: it hurts what has a Health, and goes whatever it hits.

  1. In Bullet, add void OnCollisionEnter(Collision collision).
  2. Inside, if (collision.gameObject.TryGetComponent(out Health health)), call health.TakeDamage(damage);.
  3. After that if, call Destroy(gameObject);, so a bullet that hits the wall goes too.

Press Play and shoot the dummy and the wall. Then Check.

Try it yourself

using UnityEngine;

public class Bullet : MonoBehaviour
{
    [SerializeField] private int damage = 2;

    // on a hit: damage what has a Health, then destroy the bullet
}

All lessons in Physics and Gameplay

Practice on your own: Unity playground