Creating Collectables in Unity

Objective: Create collectibles for the player to collect and have a UI element to display the number of collected items.

The first step is to add the game object that will be the collectible to the scene. This game object should have a rigid body with gravity off and a collider that is marked as a trigger.

Add a text element to the hierarchy by right-clicking and selecting text under the UI tab. This will also create a canvas. Make sure to set the UI scale mode to scale with screen size.

Position the text element in the top left corner and anchor it there. You can also change the text to say what need it too.

Make sure the overflows for the text element are set to overflow to prevent the text from getting hidden when there are too many characters to fit in the text box.

Now you will create an empty game object that will be your UIManager. Make sure you zero out the position of the empty game object.

Create two new scripts for the collectible behavior and the UIManager.

Now open the UIManager script and make it a singleton to allow the other scripts to easily access UIManger’s methods.

Add the namespace UnityEngine.UI to allow this script to interact with UI elements.

Create a variable that will hold the text box and then create a method that will take an int value and display it in the text box.

In the Player script create a variable to hold the number of collectibles the player has collected. Create a method that will increment the variable by one and then call the UIManager method.

In the collectible script use the OnTriggerEnter method to detect when the collectible has been triggered by the player. When the collectible is triggered, call the method you made in the Player script and destroy the collectible game object.

The last thing you need to do is add the scripts to correct game objects and fill in the text box with the text box in the hierarchy.

Now you should have a working collectible system.

--

--

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