Nerd For Tech
Published in

Nerd For Tech

Creating Collectibles in Unity

Our next challenge given to us was to have the player collect the coins and update a UI on the screen.

I began by creating a collectible script and attaching it to the sphere/coin

We’re just starting the script so we’ll just make an initial check to see if what’s hitting the collectible is the player and if it is, then we print that the player has a coin and destroy the coin object.

So let’s see what we have so far.

Great! So our ‘coin’ disappears and we get an acknowledgement from our OnTriggerEnter method, that we will be getting a coin!

Next, let’s go to the player script and create a new variable called _coins.

While we’re at it, let’s make our player a singleton. That’ll make things easy.

Awesome! Now the player will be super-easy to access from the collectible and UI script.

We’ll also make a method for the player to increase his coinage:

So let’s go back to the collectible script and give the player a coin!

Great! So let’s see if our player is now actually collecting coins:

Yes! If you look at the Inspector, the coins variable increases by one every time the player collects a coin! half-mission accomplished!

Next, we’ll need to place a UI canvas on the screen and access it via a UIManager script which we’ll attach to the canvas. You can skip a few steps by just creating UI/Text and it will create the canvas for you. Also be sure to rename the text CoinText or something recognizable.

From here, we just adjust the position of the text, change the color to white, make it a smidge bigger and resize the box so it fits and we anchor it to the upper left side. We also change the initial text to Coins: 0 or just leaving it blank works as well.

Let’s make the UIManager a singleton too. They make our lives easier.

Since we’ll be accessing the UI, let’s add the namespace.

Next, let’s create a holder for the UI Text object:

Naturally, we’ll drag our actual text object into it now:

Now let’s create a function that the player can access to update the UI.

As you can see, we’re going to pass in an integer called coins and then display it in the text. Easy-Peasy!

Back in the player, let’s initialize coins to 0 in the Start() function.

And place this line in our Update() function.

And let’s see it in action:

Well, our player met an unfortunate demise but on the bright side, we knew how many coins they acquired in their very short life! So there you have it! A collectible coin system that communicates data among different classes!

It would be nice if the camera followed the player, let’s talk about that tomorrow!



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