Collecting coins
Objective: Allow player to collect coins and display the coins in the user interface.
Create a user interface (UI) to display the coins collected in the upper left. From the hierarchy window right click and select UI > text, naming this text Coin_txt. In the rect transform component set the anchor to top left and using Unity move tool position the text in the canvas, as shown above. Change the text component text to “Coins: 0” and font size to 20. Adjust the color to be white.
A Canvas was also created with the text as the parent of Coin_txt. Create a C# script called UIManager and add it to the Canvas. Add using UnityEngine.UI to access the Text class. Add the Text _coinsText variable using serialize field to assign Coin_text to this variable in the inspector. The UpdateCoins method expects an int input coins and updates the text display.
The UpdateCoins is called from the player script. Add a new variable private int _coins and a private UIManager _uiManager reference to the Player script, shown below.
Add a void CollectCoin() method to Player script which increments the _coins by one and calls the _uiManager.UpdateCoins method, which passes the coin count to the UIManager.
The CollectCoin method on player is called from the Coin script, shown below. Create a new C# script Coin and attach it to the collectables, which have all been renamed Coin. The Coin script contains an OnTriggerEnter method which detects collisions and if other is tagged with Player then calls the CollectCoin method on the Player component of the other game object. The Coin game object is then destroyed.
These scripts allow the player to collect coins. The UIManager could have been accessed through the Coin script. To minimize the number of GetComponent calls, decreasing run time, the _uiManager is called via the Player script .