Pickups
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 17 of 71.
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
EasyMake the ammo crates refill the Blaster (ammo 4, maxAmmo 10).
- In
Blaster.cs, addpublic int AddAmmo(int amount):int taken = Mathf.Min(amount, maxAmmo - ammo);, add it toammo, log"Ammo: " + ammoand returntaken. - In
AmmoCrate.cs, whenother.TryGetComponent(out Blaster blaster), callblaster.AddAmmo(amount);andDestroy(gameObject);.
Press Play and walk right: the Console shows Ammo: 7, then Ammo: 10. Then Check.
Try it yourself
using UnityEngine;
public class AmmoCrate : MonoBehaviour
{
public int amount = 3;
void OnTriggerEnter(Collider other)
{
// The player's Blaster takes the ammo, and the crate goes
}
}
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 WallPractice on your own: Unity playground