2.D Platformer: Collectibles

Today, I added the ability to collect coins!

Each collectible game object has a coin script attached.

I want that player to collide with a collectible that has the property of a trigger collider.

I check if the player collided with the coin. If it has, then we want to call a function in the player script to add a coin. The coin variable in the player script will increment each time the player collides with the coin. Then we want to destroy the coin.

private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
var player = other.GetComponent<Player>();
player.AddCoin(_amount);
Destroy(gameObject);
}
}

I also created a UI Manager script that will display the number of coins collected on the top left corner of the screen.

The UI Manager script will communicate with the player so that it can grab a function to get the number of coins.

_coinText.text = "Coins: " + _player.GetCoinAmount();

If I hit the play button and pass through a collectible, we can now collect them!

That is all for today. Thank you for your time!

Gabriel

--

--

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
Gabriel Perez

Gabriel Perez

102 Followers

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.