2D Mobile: Loot System
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)
Player _player = other.GetComponent<Player>();
if(_player != null)
} 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>();
The LootDrop() will be called when the enemies health is zero or below.
if (health <= 0)
isDead = true;
Enemies can now drop loot when I kill them!