Bullets That Hit
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 56 of 71.
Challenge
MediumWrite the bullet: it hurts what has a Health, and goes whatever it hits.
- In
Bullet, addvoid OnCollisionEnter(Collision collision). - Inside,
if (collision.gameObject.TryGetComponent(out Health health)), callhealth.TakeDamage(damage);. - After that
if, callDestroy(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
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall3Triggers
Trigger CollidersOnTriggerEnterPickupsCrates Keep the RestKill ZonesEnter and ExitRecap: Key and Door6Raycasts
Physics.RaycastRaycastHitGround Check with a RayLayers and LayerMaskLine of SightOverlapSphere and SphereCastRecap: Laser Tripwire9Enemies
Chase the PlayerChase in RangePatrol and ChaseHealth and DamageBullets That HitKnockbackRecap: Guard DogPractice on your own: Unity playground