Creating Collectables in Unity

Simon Leen
2 min readAug 19, 2021

--

Objective: Create the collectable logic

Following on from the last post, we now move on to the collectables. For this we will need to implement some UI elements aswell as the collectable logic. We start by creating a coin script and adding it too each collectable which will also be renamed to coin. We set up an OnTriggerEnter on the coin script and check if the other is Player. We then get a reference to the Player and null check before calling to the Players AddCoins method which we create next.

We create a private int for coins on the Player script followed by the mentioned AddCoins method, which we will use to update the coins when the Player triggers the OnTriggerEnter on the coins script before destroying the coin.

Next we create a UIManager script to manage UI elements and logic. Inside this script we create a public method for UpdateCoinsDisplay which takes in an interger variable.

To access this script and method from the Player we create a private UIManager inside the Player script and assign it using GameObject.Find and GetComponent in the Start method along with a null check.

Next we start on creating the UI. Right-click inside the hierarchy and create UI text element. This will automatically create a Canvas and EventSystem. We will add the UIManager script to the Canvas. We then rename the text element to Coins and position it anchored in the top left corner. The Canvas gets set to scale with screen instead of pixels.

in order for the UIManager script to be able to update the UI text we need to use UnityEngine.UI. We can now create a serialized private text for the coins and assign it in the Inspector to the coins text element. We can then in the UpdateCoinsDisplay method set the UI text to a string with the passed through Player coins value.

In the next post we will look at the moving platform.

--

--

No responses yet