Menu
CoddyTech

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 icon

Challenge

Easy

Make the ammo crates refill the Blaster (ammo 4, maxAmmo 10).

  1. In Blaster.cs, add public int AddAmmo(int amount): int taken = Mathf.Min(amount, maxAmmo - ammo);, add it to ammo, log "Ammo: " + ammo and return taken.
  2. In AmmoCrate.cs, when other.TryGetComponent(out Blaster blaster), call blaster.AddAmmo(amount); and Destroy(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

Practice on your own: Unity playground