Collectibles in Unity

Daniel Kirwan
3 min readJul 26, 2021

--

Objective: Create a simple collectible for my 2.5D project

Above you can see the outcome. I have a primitive shape of a sphere that I am using as my collectible.

The first thing to do is to set up the text area for the UI that will show the player how many coins they have collected.

If you do not already have a canvas for your UI then right-click in the hierarchy and click UI -> Text and this will create the Canvas object that the UI elements will be attached to. If you already have a canvas you can right-click on the canvas and add the text object.

Once you have arranged your text where you want it, it is now time to move to coding the implementation of updating the text when the player collects a ‘coin’.

I have created a script called Coin and attached it to my sphere prefab and saved the script to all the collectible prefabs. I then created a UIManager script that will handle the updating of the text on screen.

Coin.cs code

With the Coin collider being a trigger I need to use the OnTriggerEnter method. This is checking for the tag of the collided object, if it is the player then I am getting the component of type Player(which is Player.cs) and I am running a new method called AddCoins.

Inside Player.cs

The AddCoins method is pretty simple. I am updating the coins variable inside the player script by incrementing it and then I am calling another method that is inside the previously mentioned UIManager class.

For this to work, I need a reference to the script:

I created a private variable and then inside the Player.cs Start method I am grabbing the component that I need for the reference. I am then null checking to make sure that if the UIManager is null, I get a debug message. I then update the UI with the current lives. Which at the start of the game will be 0.

The last part of coding to do is to set up the method in the UIManager class.

I have a serialized field that is for the coinText and the Lives Text. You can see in the method that the only thing that I am passing through is the current number of coins to be displayed.

The very last thing to do is to save all the scripts and go back into Unity.

Remember to drag in the coin text and lives text if you have one to the serialized field. I have my UIManager script on my canvas.

And that is it for this article. I hope it helps.

--

--

Daniel Kirwan
Daniel Kirwan

No responses yet