Creating Collectables in Unity

Andrea Zilio
3 min readJul 18, 2021

--

Time for another standard feature in a 2.5D platform game: the collectables.

Preparing the coin object

We have earlier created spheres as placeholders for our coin. Make sure they have no gravity, but the isTrigger is selected. Override to apply it to all the coin instances.

Collecting things is only fun, when you see the results. Thus when the player collects the coin, we want to show it in the UI.

We need two new scripts:

  • Collectable Script which manages the coins behavior
  • UI Manager Script which updates our UI

Collectable Script

In the collectable script we are going to detect whether our player has collected the coin. In terms of unity we check for an OnTriggerEnter. As we are in 2.5D we use the 3D collider. So our pseudocode looks something like this:

//if the player triggers the coin
//add the coin to the player coin score
//update the UI Manager text
//destroy the coin object

and the code:

Collectable OnTriggerEnter

As you can see I added some safety measures for debugging. Checking whether the player is there. The second null check can be deleted later on.

Adding a Canvas and Text

To display the coin score we add a UI Canvas and simple text in Unity

Adding a canvas and text.

We adjust the text to and anchor it to the left top corner.

Text UI Element to hold the coin score

UI Manager Script

We add a UI Manager script and either add it to a UI Manager or here I will simply attach it to the canvas object. Remember that whenever we want to access the UI in a script we need to add the UI library in the script:

using UnityEngine.UI;

We add a method to update the text:

Updating the Player Script

As we are going to create a method to update our coin score here, we first need variable to store the to the UI Manager script:

In the start method we can now use getComponent:

Here again, for debugging purposes I added a null check.

Now you might remember we called a method AddCoins() in the collectable script. We add it to the player script:

It both updates the coin counter and passes it to the UI Manager.

And that’s it. We created a collectable feature for our platform game.

The next step will be the platforms. They are pretty static right now. Now to get them moving a bit.

--

--

Andrea Zilio

Passionate Game Developer and Learning Expert. I love to create games and interactive experiences using Unity, Articulate, C#, JavaScript, PHP, HTML, CSS.