Time to add in some lovely gold!
Objective: Creating Collectables in Unity
It really doesn’t have to be gold but adding in some currency to a game can always make things interesting. We can also use this currency as a test to see if the player has collected them all before being able to move onto the next level.
Starting out on our 2.5D platformer all we have at the moment is the platforms and a bit of movement. Next, we want to add in an objective, like collecting some gold!
Since we are using a character controller, we will have to add the rigid body to the Coin to pick up but apart from that, it’s about the same as what we have done before.
Updating the UI:
Here let’s use the Singleton pattern we learnt in the last project. This should make it easier to update the UI later on.
Just a quick refresher on how it’s made. We will need 1 private Static UIManager to store the instance which no one else can change. A public static UIManager that we can change to a property, allowing us to set up a get which will give us access to public methods on the manager. lastly an awake to set the private UIManager to the instance of the UIManager.
Under that, we can start making the method to be called to update the UI. Since we are using UI we need to add the “using UnityEngine.UI”
Back under the singleton, we can make a public method to update the UI. With a reference to the Text component on the canvas, we can set it to “Coins “ + the amount that gets sent when the method is called.
If you haven’t already made one we can add one in now. Right-click in the hierarchy then click UI then select Text, this will add a canvas for us.
After that, we can move the text to where we want to see it and change its size to fit.
Let’s set up the player to call the UIManager to update how many coins we have. Here we can add in an int to store how many coins we have and inside a new public method (to get called when we pick up a coin) we can add 1 coin and call the method on the UIManager passing in the new total coins.
The last thing to set up is the coin, we already have the prefab with all that is needed. Now we just need to add in a little code so when the player walks over the coin it calls that update coin count.
Using the on trigger enter and checking if it’s the player, we can then use a get component call on what we collided with to get the player's script. After that, we can call the update coin count if the player isn’t null of course. Afterward, we can destroy the coin to make it look like we picked it up.
Now to test it out to see if it’s all working.
Perfect!! Now we can move on and start on some of the level parts, maybe moving platforms next time? Guess you will just have to stick around and find out! See you in the next one!!