- Home /
How to use FindGameObjectWithTag to get 0
I've been trying to use a simple script to count the number of GameObjects to print to a GUI. I can't figure out how to properly do it. My difficulty is that Length always returns 1. How should I change this code?
public static int count = 0;
private GameObject[] getCount;
void Update () {
getCount = GameObject.FindGameObjectsWithTag("BallsTag");
count = getCount.Length;
}
I don't see anything wrong with this code. Are you sure there are no game object with the tag 'BallsTag' in the scene? Perhaps you have a ball in the scene you use to Instantiate() from?
You could print the name of the object and its position, that would tell what and where it is.
Answer by plzburnthis · May 20, 2014 at 03:26 PM
////////Edit: I missed how I fixed my problem, the text below is not the solution/////////
Thank you to both of you for replying to my unclear question. The answer turned out to be that because I was using this script to destroy object itself:
void OnBecameInvisible()
{
DestroyObject(gameObject);
}
The final object was destroyed/removed from hierarchy but not completely disappearing. I fixed my problem by changing the code to:
void OnBecameInvisible()
{
DestroyObject(this.gameObject);
}
Actually, both code are the same. Your fix is from somewhere.
The this keyword is just a pointer to the actual object calling the method, in your case, the script on which it is called. The script inherits gameobject reference from $$anonymous$$onoBehaviour, so using this.gameObject or simply gameObject result in the same.
Your answer
![](https://koobas.hobune.stream/wayback/20220613145417im_/https://answers.unity.com/themes/thub/images/avi.jpg)