Create a Loot System in Unity — A Diamond in the Rough
We should reward the player for killing enemies. We’ll create a simple loot system where killing a monster spawns a gem that perhaps the player can later use to buy useful things. We have a sparkling diamond in our sprite sheets.
We’ll use OnTriggerEnter2D to reward the player.
public class Diamond : MonoBehaviour
{
[SerializeField] int _diamondValue = 1;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.TryGetComponent<Player>(out Player player))
{
player.addDiamonds(_diamondValue);
Destroy(gameObject);
}
}
}And, of course, on the player:
public void addDiamonds(int diamondValue)
{
_diamonds += diamondValue;
// Update the UI. If I had a UI.
}Get Sean Duggan’s stories in your inbox
Join Medium for free to get updates from this writer.
And, does it work? Yup (although you wouldn’t know it without seeing that value increment in the Inspector…)
Now, let’s make the enemies drop one on death.
public void PlayDeath()
{
_animator.SetTrigger("Death");
Diamond diamond = Instantiate(_diamond, transform.position, Quaternion.identity);
diamond.SetValue(_gems);
_isDead = true;
}Small problem, the player is “touching” the diamond when it gets instantiated, so it’s getting destroyed and then we try to set the value… and we get an exception. So we’ll add a short delay before we allow the diamond to be picked up.
public class Diamond : MonoBehaviour
{
[SerializeField] int _diamondValue = 1;
bool _isActive = false;
static WaitForSeconds _delay = new WaitForSeconds(1f);
private void Start()
{
StartCoroutine(Activate());
}
IEnumerator Activate()
{
yield return _delay;
_isActive = true;
}
public void SetValue(int gems)
{
_diamondValue = gems;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (!_isActive) return;
if (collision.TryGetComponent<Player>(out Player player))
{
player.addDiamonds(_diamondValue);
Destroy(gameObject);
}
}
}My green giant flipping sides is indeed a bug. The CombatMode is on, and it’s flipping the sprite to face the player. I added a quick exit for the Update for if they’re dead.









