How to set up simple loot system in Unity

Let’s got over how to implement a simple loot system.

In this article I will continue to add functionality to the Enemy script from this article.

First, create two scripts called InventoryManager and UIManager attach both to an empty game object in the scene:

Open up the InventoryManager script. Add using statement System. Set up class as a singleton, explained further in this article. Create int property for gems and add an Action delegate to call when the amount changes. Call OnGemAmountChange in the start method to ensure that the UI will be correct. Add a public function for updating the UI amount:

Open up the UIManager script. Add the using statement UnityEngine.UI and also turn this class into a singleton. Add a serialized field for the gem text. In the Awake function subscribe to the OnGemAmountChange delegate and create the UpdateGemUI function:

Add the gem text to the script on the Inspector:

Create the loot object from an empty game object. Add a sprite renderer, a box collider and a rigidbody. If your sprite has animation frames add an Animator as well:

Create a script with a suitable name and attach to the game object:

Open up the script and add a serialized int for the amount of gems this object will give. Add an OnTriggerEnter2D function and update the inventory with the amount of gems. Also add a public function for setting the amount of gems:

Open the Enemy script. Add an int for the amount of gems the enemy will give out, GameObject for the loot prefab and a Transform for the position where the loot will get instantiated:

Add a public function for dropping the loot:

Open up the EventReceiver script to call the DropLoot function:

Lastly, add the event to the Death animation of the enemy:

Good luck!

Unity / C# Game developer