Collectable Objects in Unity

Get money

Gonna buy me a stairway to heaven.

… okay, digression over. Back to the Unity 2.5D platformer.

What is a platformer without collectable objects? Why the heck would you do all that jumping about if it weren’t to obtain some loot? Even when Nathan Drake is running for his life, there’s usually some shiny object in his path.

This is possibly my greatest photobash.

Nothing is more iconic than the shiny golden coin. We’ll start by creating a new material named Coin_mat. Make it an orangey sort of yellow — too cool of a yellow and it can start to look green when we crank up the Metallic map. Also, crank up the Metallic map and give it about 85% Smoothness.

Yeah, that looks rich.

Next, create a new sphere primitive, set its z-scale to 0.1, and rename it to Coin. Add a Rigidbody component with Use Gravity off, and set the Sphere Collider to Is Trigger. Also slap that Coin_mat material on there.

We can toss a few of these into our prototyping scene, and now we have something worth jumping for.

I wonder if they’ve got a chocolate filling…

From here we need to script the collectable behavior. Create a new C# script and call it Coin. Inside, there is just a simple instruction in an OnTriggerEnter (Collider other) method:

if I collide with a player,
tell the player to run their AddCoins() method,
destroy myself.

In C#, this looks like:

The Player script needs this AddCoins() method now.

Great. Now we can collect our coins. But, how does the player know how many coins they have? We’ll need UI for this. And with constantly updating UI, we’ll want a UI manager to handle the traffic.

I’ll create a new canvas, and add a UI Text object to it called Coins_text. The default text can be “Coins: 0" with color black, font size of 34 or so, and turn on the horizontal & vertical overflows.

Create a new C# script called “UIManager” and attach it as a component of the Canvas object in the scene. Open it up, and prepare a Singleton for instancing the manager in static memory.

Then add a new property (above Awake()) that allows us to set the property to rewrite the text of Coins_text.

If you don’t like serializing fields, you can also set the handle in the Awake() method by searching through the Canvas’ children.

Now we add one line to the Player’s AddCoins() method:

There we have it. Now, let’s grab some loot.

Think of all the things we can do with FIVE money!

Oh, yeah. That’s the stuff.

Hey, you notice that sweet moving platform? I’m gonna talk about that tomorrow in my next article. Until then.



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