Coin Collection Counter

I am a moderate C# coder but don’t have much experience with UI. I received the following code from a friend but am facing some bugs:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class collection : MonoBehaviour {
	public Text countText;
	public int coinNum;

	void Start () {
		coinNum = 0;
		countText.text = "Count: " + coinNum.ToString ();

	void OnTriggerEnter2D (Collider2D other) {
		if (other.gameObject.tag == "bonecoin") {
			other.gameObject.SetActive (false);
			countText.text = "Count: " + coinNum.ToString ();

	void Update () {
		countText.text = "Count: " + coinNum;

I am able to see the counting total in the Inspector window when I select the player, but the text is not updating each frame. Also, when I exit play mode, the text updates.

For example, if I enter play mode and collect 5 coins, I won’t see the text say “Count: 5” like it should. However, once I exit play mode, I see the text read “Count: 5”. The text continues to stay that way until I enter and exit play mode again. The text doesn’t even change when I enter play mode and start the game.

Before I posted this, I looked up many things to try and find a way to fix my problem including some other great questions posted on this site, but none of them helped.

Hmm, this jiggles a thought as I just went through the 2D UFO Game tutorial a day or two ago. Is your counting text a child of a Canvas element in the hierarchy? I seem to recall some mention of not being able to see the text render on the screen if it’s not in a Canvas element. When you add a UI Text element to the hierarchy, it creates new Canvas and EventSystem objects if they didn’t exist before and places the new Text element under the Canvas.

One other small note - it would probably make sense to put the text update in a function that you can call from multiple places to eliminate duplicate code. I noticed your code in Update wasn’t converting coinNum to a string, while the other places were converting it. :slight_smile:

Hope this will help: Unity | Coin collection system with Coin collecting Animation - YouTube