Creating simple UI Elements for your game
What are the main UI Elements you need for a game?
For Space Shooter 2D, there’s life count and score.
And these are pretty simple to do.
Player live Count
For player live count we have 4 different sprites. 0, 1, 2 & 3 lives sprite. This determines how many lives we have. And we have to change the sprite when our live count drops from 3 to 2 and so on.
To control our UI, we need a UIManager script. Then we need a Lives_display_img which we control from our UIManager when we get hit.
Our Lives_display_img is anchored to the left upper corner.
In our UIManager we need a private sprite array where we store our sprites.
And it looks like this in our Inspector, then you add your sprites in order.
We also need private Img for the Lives_display_img
In our UIManager we have UpdateLives() method. Which takes integer currentLives.
Our _LivesImg.sprite is equal to the _liveSprites[currentLives]
Where we store our live sprites (0,1,2 & 3) Our live count is 3 when we start. If we take 1 damage our currentLives will be 2.
So we take the element 2 sprites from the array and change it to the _LivesImg.sprite.
But our UIManager needs the information somewhere to know how many lives we have. And that we do from the player script where we damage the player.
Our Damage method has _lives integer which we pass forward to our UIManagers UpdateLives(int currentLives).
The name isn’t important, you need to give the UpdateLives integer and it should work! :)
For our score, we need private Text _scoreText which we will manipulate when our player destroys the enemy.
We have the same kind of method for our score as we had for our lives.
AddScore(int points) takes an integer and adds it to our _score, then we update the _score to our UIManager UpdateScore.
This is the code we have in UIManager
UpdateScore takes an integer which is the points from AddScore method in the Player Script.
And our _scoreText.text is “Score: “ + our playerScore changed into a string.
So how does our player know how many points it will get?
You could manually just write 10, 20, or even 30.
But since the AddScore takes an integer. We can write in our enemy script when it destroys, that it will give our player a certain integer which will be our points.
Awesome! Lots of playing with integers and script communicating.
If script communicating is not that familiar subject, I recommend checking this article.
Thank you for reading! See you in the next one! Ready… Set… GO!