I have a script where I am trying to count how many objects are on screen with a certain tag…
Every time I introduce a new object with the tag it increases the count by 1… But it doesn’t subtract ones that get destroyed. Instead it just keeps track of how many have been on screen…
This is in Update so I figured it would work both ways but it doesn’t.
What is the proper way of doing something like this?
Can you show us the code? Use the CODE tags properly when showing us your code.
The objects that get Destroyed, you can put something in their OnDestroy() function that announces they are being destroyed, so whatever is keeping track of counts can remove 1.

As you can see I have been trying to basically beat this idea into working… the ballsDead = GameObject… line is there because on ocassion it will return a negative number somehow so this was put in place to avoid that…
All in all this method is awful and doesn’t work properly at all…
I wanted to just put the information in a GUIText and hide it from view perhaps but I don’t think that is an effective way either.
void Update ()
// Trying to determine amount of balls on screen so that the
// game only takes away a life when the last ball is destroyed.
{
ballsLeft = GameObject.FindGameObjectsWithTag("ball").Length;
if (ballsLeft - ballsDead < 1) {
ballsDead = GameObject.FindGameObjectsWithTag ("ball").Length;
}
}
// Checking to see if the object that hit the DeathField
// Is in Fact a Ball
void OnTriggerEnter( Collider other){
Ball Ball = other.GetComponent<Ball> ();
if (Ball) {
ballsDead++;
Debug.Log(ballsLeft-ballsDead);
if(ballsLeft-ballsDead <= 0){
Ball.Die ();
}
}
There are a lot of ways to do this.
The simpler way to do this is to put a static int in your Ball class. Ball.ballsLeft would always be how many balls are left. Would that accomplish what you need?
EDIT: Made Ball extend MonoBehaviour
public class Ball : MonoBehaviour
{
public static int ballsLeft {
get {
return m_ballsLeft;
}
}
private static int m_ballsLeft = 0;
void Awake() {
m_ballsLeft++;
}
void OnDestroy() {
m_ballsLeft--;
}
}
How I would do something like this in a large project is to have a BallManager class that Instantiates and is in charge of keeping track of all Balls. The Balls would fire an event whenever something interesting happened that the BallManager should know about.
The BallManager class would probably be the best route to go… I need to move quite a bit to make that happen. But I guess it’s best I do that