2.5D Phase1 Framework: Collectible
Why not create coins as a collectible?
2.5D Phase 1 Framework Challenge
For today's challenge, I implemented a collectible item for the player. It’s a coin that increments when the player collides with it.
What Do I Need?
I need a coin game object. I also need to create a script for the coin so that I can tell it to detect the player, increment the coin count, and destroy itself. I will also need to create a UI Manager script so that I can update the count on display.
Getting Started
I searched in GameDevHQ’s Filebase for a coin model and found this:
I also took the liberty to animate it in Unity. I wanted it to spin and move up and down as if hovering.
I then created a script called “Coin” and attached it to the Coin game object. I want it to detect the player on collision enter.
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag(“Player”))
{
var player = other.GetComponent<Player>();
player.AddCoin();
Destroy(gameObject);
}
}
When the player collides with the coin, I want to call AddCoin() from the player to increment coins. Then I want to destroy the coin game object.
In the Player class, I added a variable for the coin:
private int _coins = 0;
I also added the AddCoin() method:
public void AddCoin()
{
_coins += 1;
}
When this method is called from the coin class, it increments coins.
I also want to add another function that returns the value of coins. This will be needed for the UI Manager class.
public int GetCoins() => _coins;
I went ahead and created a UI text element for displaying the coin count. I also created a UIManager script and attached it to the canvas of the coin text element.
The UIManager class will hold a reference to the coin text and the player. I want to expose the coin text in the inspector so that I can drag the coin text game object to the inspector.
[SerializeField] private Text _coinText = null;
private Player _player;
In Update, I want to access the text component and assign a value to display “Coins: <coin value>.” The coin value is returned from the GetCoins() method created in the player class.
private void Update()
{
_coinText.text = “Coins: “ + _player.GetCoins().ToString();
}
With all of this set, we now have a collectible that can be collected by the player and have it incremented on the screen!
Gabriel