Spawn collectibles on enemy death in Unity

Daniel Kirwan
2 min readSep 17, 2021

--

Objective: Spawn collectible prefabs that will have a different value based on the enemy type

In my project I have three types of enemies that are derived classes of the enemy class. I have MossGiant, Spider and Skeleton. I want to give the player an item drop when the enemies die, and I decided upon a diamond that will give the player a different amount of ‘money’ based on the enemy type.

The spider will give 1, Skeleton 5 and the moss giant will give 10. With the way that my classes are set up, this is a pretty easy thing to accomplish. The base Enemy class has a gems field that is accessible in the Unity editor.

First I created a new Diamond class that has a standard gem reward of 1 and it does two things, updates the value of the gems and it will award the player that amount when collided with.

Before the above can be used I needed to update the player class to contain a new diamond field which is initialised to 0 and a new method that will update the diamonds in the player. As you can see above in the nested if statement, this is where I am calling the new UpdateDiamonds method.

Next, is to update the enemy class with spawning the diamond on the enemy death and also updating the diamonds value before the enemy is destroyed.

Here you can see the new method in the enemy class, my spider has a different set up for taking damage so the spider is calling this method in its class and not inside the base class.

And that is it for allowing the enemies to spawn a collectible for the player.

--

--

Daniel Kirwan
Daniel Kirwan

No responses yet