Creating Collectables in Unity

There are essentially 2 parts to creating a collectable; The removal and the impact of the collectable.

In order to begin, let’s create a sphere which will be used as a coin, and create a coin script:

After attaching the “Coin” script to our sphere, let’s open up the script. The first thing we need to do is to check to see if there is a collision with the player…we can do that in the OnTriggerEnter method:

If we want to destroy the object, we can substitue the commented out line for “Destroy(this.gameObject);”. With the collider set as “Is Trigger”, the result would look something like this:

The result looks like we have collected the ‘coin’. If we want to turn this into a score, there is a little more work involved.

Back in the coin script, we will add a value of 10 to each coin, and an Action with the value passed in…this way we can simply announce that a coin was collected without having to find objects or get components:

Make sure to include “using System;” at the top of the script when using Actions

We are now ready to send events when coins get collected but we need to make sure someone is listening. Let’s create a UIManager that will hold a Text element and keep track of the score:

Make sure to include the “using UnityEngine.UI” when using UI elements

When we created the Action in our coin class, we need to create the same signature in order to listen for that action. We also need to subscribe to the event when our UIManager is enabled and unsubscribe from it when we disable the class:

The end result should look like this:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store