Make Your Own Pickup
๐ฏ Goal
Write a pickup for ammo, power-ups or anything else collected on touch.
๐งฐ What You Need
- A script that derives from
Pickup
๐ช Steps
Derive from Pickup
Create a script that derives from Pickup and implement Apply. It runs on every collision, with the Collision that touched the pickup.
using GlowingRifts.ModularHealthSystem;
using UnityEngine;
public class AmmoPickup : Pickup
{
[SerializeField] private int _ammo = 30;
protected override bool Apply(Collision collision)
{
AmmoPouch pouch = collision.collider.GetComponentInParent<AmmoPouch>();
if (!pouch || pouch.isFull) return false;
pouch.Add(_ammo);
return true;
}
}AmmoPouch stands in for your own component.
Return true when collected
Return true when the pickup was used, and false to ignore the collision, for example when the wrong object touched it or the collector is already full. Only a true raises On Collected and destroys the pickup.
Keep it in the scene (optional)
Override destroyOnCollect to return false for pickups that stay and work on every new touch, such as a recharge pad.
protected override bool destroyOnCollect => false;Hook On Collected
Add the script to a GameObject with a solid collider, then hook On Collected to a sound, an effect or a Hitpoint’s ShowText. It passes the collector: the Rigidbody’s GameObject when the collider has one.
๐งช Example
DSPowerUp in the Modular Weapon System’s Duck Shooter example is a Pickup that gives the ship a new weapon. Its Apply looks for the player on what it touched and returns false for anything else. It also overrides OnCollisionEnter to call TryCollect and destroy itself when it falls onto something without a Rigidbody:
protected override void OnCollisionEnter(Collision collision)
{
if (!TryCollect(collision) && !collision.rigidbody)
Destroy(gameObject);
}HealthPickup itself is built the same way.
๐ก Tips
- Collisions need a non-kinematic Rigidbody on one of the two objects, and the pickup’s collider must not be a trigger.
- Call
TryCollect(collision)yourself when you overrideOnCollisionEnter, or the pickup won’t be collected. - Use
GetComponentInParenton the collider, so a hit on any child collider still finds your component on the root.