How do you fix a script so that it counts when a tagged object is destroyed.

Hi, I’ve built a script that is supposed to display a counter of similar tagged objects, so when they collide with a ball shot from the camera, the counter goes up until all 12 are counted, and the “You Win” message is shown.
This is the script:

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

public class TinCansDestroy : MonoBehaviour {

		public Text countText;
		public Text winText;

		private int count;

		void Start ()
		{
			count = 0;
			SetCountText ();
			winText.text = "";
		}
		
		void OnTriggerExit(Collider other) 
		{
			if (other.gameObject.CompareTag ("TinCanDestroyed"))
			{
				other.gameObject.SetActive (false);
				count = count + 1;
				SetCountText ();
			}
		}

		void SetCountText ()
		{
			countText.text = "Tin Cans: " + count.ToString ();
			if (count >= 12)
			{
				winText.text = "You Win!";
			}
		}
	}

The tagged objects (12 of them, duplicates of the same object) have the tag TinCanDestroyed. The script is attached to an invisible object in the scene. The countText and winText are linked to UI Texts attached to the canvas. The problem is that when the scene goes into play mode, the counter remains at Tin Cans : 0 no matter how many Tin Can objects are collided with by the ball. How do I fix this? What am I doing wrong?

  1. The script has to be attached to one of the objects that is part of the collision to make unity call your event method. So as you are already checking for the tincan tag, you should probably attach it to the ball.

  2. You could then have a singleton script attached to the invisible object with a public static method that is called by each of the balls (that will now have your collision script) whenever the ball collides with a tagged object.

  3. The method should probably be OnCollisionEnter() and not OnTriggerEnter() as you won’t get physical collisions using trigger colliders. Unless you just want the tincans to immediately vanish on contact.