Loot System: Part One — Diamond Behavior!

addam davis
4 min readDec 9, 2021

Objective: Create a collectable and give it behavior!

In this game I’m going to have the player collect diamonds which will be used as a currency to buy items from a shop needed to finish the level. We are going to have our enemies drop diamonds according to their gems value. The enemy will drop the diamond and the diamond will have a behavior to determine it’s value.

Take your sprite for your collectable and slice this using the auto slicer.

Take the first sprite and drag into the Hierarchy.

Set the order in layers to the same as our player and for us that would be 50.

Make this a prefab by dragging the object into a prefab folder.

Create a new script for the diamond and drag that onto the diamond prefab.

Also add a collider and rigidbody, make sure it is a trigger and the gravity is set to 0.

Now it is time to work out the code. Open the diamond script and delete the default methods.

This is the pseudo code. This is what we want to do with this script.

Starting from the top we need an on trigger enter 2D method. As well as a variable representing gems value.

We need to check for the player.

We need to add value of the diamond to the player so we need to navigate to the player’s script. The player needs a variable to represent the amount of diamonds they have.

We can now continue on the diamond class, we need a reference to the player.

If the player collides with a diamond, the diamond will get the player component. If we do a null check for when the player is not null, we then manipulate the player’s diamond variable. Once we have done that we can get rid of the diamond to give the illusion of the player collecting the diamond.

Now when our player collides with a diamond the player’s diamond value with increase and the diamond will be destroyed.

Now we have a working collectable. In the next tutorial we are going to continue on our loot system by creating logic for our enemies to drop these diamonds set to different values depending on the enemy that drops them. Don’t be afraid to experiment with your collectable and I’ll see you in the next tutorial!