Create a Loot System in Unity
Objective: Create Loot System
Every game needs some form of loot. For this one we gave diamonds.
We follow the same process to create a prefab with an animation for the diamond then create a script for the diamonds.
We start by adding a public variable inthe player script for diamonds. Next we create set up the diamond script with an OnTriggerEnter to check for the Player before executing the required logic to collect(destroy) the diamond after giving the Player the required/earned rewards.
We want the enemies to spawn diamonds when they die so to allow all enemies to use the diamond prefab we can add a public GameObject for the prefab in the Enemy script which will be accessible to all the enemies.
Each enemy has been set up initially to hold a different amount of diamonds/gems which can be set per enemy in the inspector. For this the Spider is worth 2, the Skeleton 3 and the Moss Gaint 5. When the player kills the enemy a diamond will need to be instantiated and that single diamond will be worth the value of the enemy gems.
Before this, we need to fix a small bug. Currently after we kill an enemy, it can be killed over and over again as we have no guard set to control after the enemy has been set as isDead. It also allows a new diamond to be instantiated each so called kill.
By just adding a simple if isDead return to the start of the method we fix this issue. Finally we instantite the diamond after the enemy is dead and set the enemy gems to be added to the Player to the value associated with the enemy that has just been killed making it more modular and dynamic in achieving the resulting loot.