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)
{
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

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Intro to JavaScript for Sportsfans-4

More Operators

The Origin of React

Common Array methods in JavaScript

How to Handle Errors in JS with try/catch

REserve — Cache and Proxy

REserve — Testing UI5 — Probing the tests

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gabriel Perez

Gabriel Perez

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

More from Medium

2D Mobile: IDamageable Interface

Take Photo with Phone in Unity

How to animate and move a simple player with Mixamo and Unity/C#

Installing Unity & getting started with game Development