Mobile Games In Unity: Spawning Gems
Once we’ve defeated the enemy we need a reward! This is a crucial part of game design. People dont play games for no reason. I want to set up a reward system for when the player defeats an enemy. So I’m going to reward them with gems. These gems will be used at a later point in the game to purchase necessary items to continue through the level.
So theres actually a little bit going on here as far as programming is conerned, so lets tackle this first.
Here is the script that is on my diamond prefab. Whenever the player collides with it the AddGems() method is called from the player script. Then the gem is destroyed. Whats happening there?
This method is passing in an int parameter called amount.
diamonds, an int defined at the top of the script += amount. I have declared this variable and set it equal to 0.
diamonds is what the player uses as currency within this player script. After we update the amount of diamonds the player has the UIManager updates the UI.
I have a Text element called gemCount that updates in the top left of the screen near the health bar when a gem is collected.
So when a gem is collided with, the add gems function in the player script is called. This has a parameter that is updated in the UI manager called
count. This sets the player’s diamond count += the current amount. So everytime another gem is collected it increments by 1.
So how do we spawn a gem when an enemy is defeated?
INSTANTIATE! If you remember from the space shooter game, I went over the process for instantiating objects. Before you can instantiate a game object, it needs to be a prefab. So I have created the diamond prefab.
To instantiate this I want to go about it a little differently. SInce my enemies all inherit from the enemy class, and they all share this functionality, I’ve declared the variable for the diamond prefab in the Enemy class.
My moss giant script contains the instantiation line.
This diamond prefab has the Diamond script on it. I’ve assigned this
int a value of 1. So I’ve instantiated this GameObject
diamond from the prefab assigned in the inspector as GameObject and I get the Diamond component (the script) and gems = base.gems. So now in my Moss giant’s inspector I can assign whatever value I want to the instantiated diamond. In this case, 200.