2.5D Platformer — #4 Collectibles

Objective: Give the player the ability to collect coins and display a count

Now that we have the player's movement in place, we need to now focus on a currency for this game and that is coins. The idea is the player needs to collect a total of 8 coins before they can call an elevator.

For my collectable, a coin, I start with an Empty object and name it Collectable and reset its position.

As a child of the Collectable, create a cylinder and rename it to GFX. This can be swapped out when I have a better 3d model for the coin but for now, change the Transform settings to the following:

Next, Create a Gold coloured Material and drag it onto the GFX.

I like to have the GFX simple as the graphics so I move the Capsule Collider off the GFX and put it on the Collectable and check Is Trigger.

Create a Collectable script, add it to the Collectable and turn it into a Prefab.

In the script, there is a OnTriggerEnter and we check if the other is the Player and if so we call the CoinCollected event and destroy the collectable.

To be a fancy pants, I made the coin rotated in the Update method.

In this article, Using Events to Destroy all the Enemies, I showed how to use Events which is what I am doing here too. In this case, the Player stores the number of coins collected and I have defined an eventOnPlayerCoinCollected that accepts an int parameter.

When CoinCollected method is called, it increments the coin amount and if anything has subscribed to the event, it passes the number of counts.

To display the coin amount on the screen, we first set up the UI and I also create a UI Manager script and drag it on the Canvas.

In the script, I first create a reference to the UI Text and drag the UI text onto the Canvas UI Manager slot.

In the Awake method, we subscribe to the OnPlayerCoinCollected event passing it the method that will handle the event when it occurs which simply passes the number of coins. We also initially set the text to zero coins.

That’s it. We now have coins the player can collect and see the amount on screen. I personally feel this is a good approach to separating the UI and Player by using events.

If you enjoyed reading this article give me a Clap, also if you would like to see more, “Follow” me, so you may be notified of future releases. You may also send me a message if you need any further help.

Do you have a project in mind that you need help with, I’m available!

A Data & Analytics Consultant who is expanding into developing experiences in XR, Enterprise and Gaming space using Unity www.jeannoelseneque.com