Day 78 — Creating the Collectable

Hey and welcome!

In this one we’ll be implementing the logic for our player to collect the spheres/future coins that we have laying around our scene. We’ll be using code here similar to the 2D space shooter when we collected powerups.

Let’s start by creating a Coin script to attach to our collectables and add in the following code:

private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
Player player = other.GetComponent<Player>();
if (player != null)
{
player.UpdateCoins();
}
Destroy(this.gameObject);
}
}

This is where we’re going to handle the code for the collision, don’t forget to set the tag of our player object to “Player” otherwise this won’t work. This code overall is pretty similar to what we’ve used before, we check for a collision with our player object as it gets stored in other at the moment of impact.

Then we can use the information stored in other in order to grab the script component off of there to run our UpdateCoins() method. Speaking of, let’s go ahead and add that to our Player script next.

private int _coinCount;
private UIManager _uiManager;
void Start()
{
_uiManager = GameObject.Find("Canvas").GetComponent<UIManager>();
if (_uiManager == null)
{
Debug.Log("The UI Manager is null");
}
}
public void UpdateCoins()
{
_coinCount++;
_uiManager.UpdateCoinCount(_coinCount);
}

Nothing too fancy with our UpdateCoins() method, just adding 1 onto the _coinCount variable and then passing that to the UIManager which we got a reference to in the Start() method.

To make that useful though go ahead and create a UIManager script and then add in this last bit of code for that.

public Text coinText;public void UpdateCoinCount(int coinCount)
{
coinText.text = "Coins : " + coinCount;
}

This bit of code visually updates some text on our game screen to let the player know how many coins they have.

Which leads us to the last part we need to do here, go ahead and add in a new text object in the hierarchy and anchor it anywhere you want on the screen and change the text in it to “Coins: 0”. When you do that it will also create a Canvas object which you’ll want to add your UIManager script to. You can also change the colour to one you prefer.

With all that done you’ll have something like this:

If it’s not working make sure to double check that the colliders on both the player and coins are set to trigger and that the coins have a rigidbody component on them.