Creating Collectables in Unity
2.5D Game Development
Objective: Collect coins and update UI to display collected coins amount
Let us start by adding spheres in our scene view which is going to act as our coin.
Then add a Text gameobject and align it to wherever you want your coin count to be displayed.
Now add another empty gameobject and name it UIManager. Then create two scripts, one Coin which will define coin behavior and another UIManager which will handle the UI side of things.
Drag coin script to coin gameobject and UIManager script to UIManager gameobject.
First of all define a singleton pattern inside the UIManager. If you ask how then it is explained here.
Now define two variables inside the UIManager script, one for accessing the Text component in coin text UI and another public variable to store the coin count.
Now update the text with the coin count inside the update method so that whenever coinCount variable value changes, the coin amount in game is updated.
Now lets create a coin behavior. Inside a coin script, create a OnTriggerEnter method which will detect gameobjects that enter its trigger. Then check if the gameobject that entered its trigger has a tag of Player, if it does then increase the coin count by 1 in UIManager and destroy the current coin gameobject.
The coin count is being changed as such because we are using singleton pattern for UIManager.
In Unity, drag the Text gameobject to the _coinText reference variable inside UIManager inspector window. With this the game will count and display the coin count with each coin collected.
And this is the final result.