Creating Collectables in Unity!

Objective: Create collectable “coins” on your platformer.

A common trope in platformers is collecting large quantities of items, like coins. In this tutorial we are going to use basic 3D shapes, you could replace with assets later.

To begin Create a sphere, prefab the sphere, and duplicate across the landscape.

Make sure the ‘is trigger’ is true and add a rigidbody with no gravity.

Create and open a script for these ‘coins’ this will be a trigger script so delete everything and create an on trigger enter method. Attach this script to all the coin objects.

In the on trigger enter method we want to check if the player hits the collider and if it does what do we want to do? We want to add a coin to the player, and delete the coin object, so navigate to the player script and create a variable to represent the coins and a method for the coin class to call upon.

Now, we have a method for the coin class to call upon when it collides with the player. The method requires an int value to be called. After we send the value to the player we can delete the coin.

In the player method we need to take that value and add it to the coin variable we created.

With the coins being stored on the player we should make a UI element to display the amount of coins collected. Right click in the hierarchy > UI > Text.

I place mine in the top left of the screen, set the font size and type a sample in the text box. You will also want to set the horizontal overflow to overflow.

Create and open a script for the UI Manager. Attach the script to the canvas. In this script we to add the UI library.

Create a text variable for the text object we just created. We also need an int variable for the coins.

In the start method we want to set the coin display to read “coins: 0.”

When the play takes a coin we need the player to tell the UI Manager to update the display. So on the UI Manager we need to create a method for the play to call. Similar to the coin method on the player the method on the UI Manager will also have an int parameter.

This method needs to add to the coin variable as well as update the text object.

When we collect a coin, the amount will be on display for the player to see, and the coin will disappear after being collected.

Now, you know how to create collectables in your platformer. As I always say, don’t be afraid to experiment with your codes and I’ll see you in the next tutorial!