2.5D Platformer: Collectibles
In this article, I’ll be setting up the spheres we have to be collected by the player and setting up a UI display to show how many have been collected.
The first thing I did was to create a UI Text object named Coins. I then changed the text body to Coins: 0 and placed it in the upper left corner of the game screen.
Next, I created a script named Collectible, which will be used for all collectible objects in the game. I also renamed the spheres to Coins in the Hierarchy and made them a prefab.
Now it’s time to jump in and start scripting the behavior for the collectibles, the text object, and the player. First, I’ll start with the Player script by adding a variable to keep track of the coins the Player has and a method AddCoin() which will be called from the coin when the player collects it.
Then I’ll move over to the Collectible script. There I need to add an OnTrigerEnter event and check if the collision is with the Player. If so, I get a handle to the Player script, null check to be safe, call the AddCoin() method, then destroy the GameObject.
Next, it’s time to set up a UIManager script on the Canvas GameObject. The UIManager will have a public method to update the Text display and will take an int as a parameter. Finally, I’ll get a handle on the UIManager on the Player and call the method when the Player collects a coin.
In the UIManger script, I’ll create a serialized field for the text object and create the method to update the coin display.
Once I save and go back into Unity, I drag the Text object into the space on the UIManager asking for a Text object.
This completes the setup for the UIManager. Now I can move on to the Player script. First, I need to create a variable for the UIManager in the Player script.
Next, I’ll use this variable to reference the UIManager script on the canvas object and null check it just to be safe.
Now that I have a reference to the UIManager, I can call its method UpdateCoinDisplay() when the Player collects a coin.
Now that everything is set, the coin display should update whenever a coin is collected.
And you can see the display updated when the first and second coins were collected by the Player just like it should.
That does it for setting up the collectibles for the game. I hope you found this interesting and informative. And as always, until next time, I wish you well on your own coding journey.