Pickups
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 17 of 63.
A pickup is a trigger with a script of its own. When something enters, the pickup checks that it is the player, hands over its effect and destroys itself. The player's script keeps the result and offers a public method for it. This health pack heals whatever has a Health script:
// HealthPack.cs
public int amount = 25;
void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out Health health) && health.hp < 100)
{
health.Heal(amount);
Destroy(gameObject);
}
}// Health.cs, on the player
public int hp = 50;
public void Heal(int amount)
{
hp = Mathf.Min(hp + amount, 100);
Debug.Log("HP: " + hp);
}other.TryGetComponent(out Health health) is false for a crate that slides into the pack, so only an object with a Health script can take it, and a player at full health leaves the pack for later. The pack finds the player through other, so no pack needs an Inspector reference, and a level can hold fifty of them. Heal is public because another script calls it, and the cap at 100 lives in Health, the one place that owns hp. Destroy(gameObject) removes the pack; Destroy(other.gameObject) would remove the player.
Challenge
EasyThe player carries a Blaster: ammo (4 at the start) and maxAmmo (10). The arrows move it and Space fires a shot, and both are written. Make the ammo crates refill it:
- In
Blaster.cs, add a public methodint AddAmmo(int amount). It takes as much ofamountas fits undermaxAmmo, logs the new total such asAmmo: 7, and returns how many it took. - In
AmmoCrate.cs, when the player enters a crate, offer the Blaster the crate'samountand subtract what it took. A crate that is now empty is removed; one with ammo left stays, with what is left, for a later visit.
The first crate holds 3 and the second 5. Press Play, walk right, fire a few shots and walk back into the second crate, then Check.
Try it yourself
using UnityEngine;
public class AmmoCrate : MonoBehaviour
{
public int amount = 3;
void OnTriggerEnter(Collider other)
{
// The player's Blaster takes what fits; the crate keeps the rest and goes once it is empty
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall