2D Mobile: Loot System

Gabriel Perez
2 min readJan 9, 2022

Enemies can now drop loot upon death!

I have an animated diamond that I want to set up for the player to collect.

In the game, they are called gems, and they will be the currency in the game. The player will be able to defeat enemies and collect gems for purchasing new abilities from a smuggler shop.

I created a Gem script and attached it to the diamond game object. I turned the game object into a prefab so that I can instantiate it when an enemy dies.

The Gem object will check and see if it has collided with the player. If so, I want to call a method from the player class where I can pass the argument of adding a number of gems. I then want to destroy the game object.

public class Gem : MonoBehaviour
{
[SerializeField] private int diamonds = 1;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag(“Player”))
{
Player _player = other.GetComponent<Player>();
if(_player != null)
{
_player.AddDiamond(diamonds);
Destroy(gameObject);
}
}
}
public void SetGemAmount(int value) => diamonds = value;
}

In the Enemy class, I created a LootDrop() method, and it will handle the instantiation of the gem and call the SetGemAmount() with a variable holding the number of gems each enemy will drop.

public virtual void DropLoot()
{
var gemsGO = Instantiate(gemPrefab, transform.position, Quaternion.identity) as GameObject;
var gemScript = gemsGO.GetComponent<Gem>();
gemScript.SetGemAmount(gems);
}
The Moss Giant will drop 5 Gems.

The LootDrop() will be called when the enemies health is zero or below.

if (health <= 0)
{
isDead = true;
enemyAnim.SetTrigger(“dead”);
DropLoot();
//Destroy(this.gameObject, 3f);
}

Enemies can now drop loot when I kill them!

Gabriel

--

--

Gabriel Perez

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.