How to get an int value of instances found by "FindGameObjectsWithTag"?

I am trying to find the number of “enemies” using “FindGameObjectsWithTag”, i then get the lenght of the array but when i print into the console it prints each instance found instead of the total.

	void Num_enemies()
	{
		GameObject[] getCount = GameObject.FindGameObjectsWithTag ("WeakSkeleton");
		int num_enemies = getCount.Length;
		Debug.Log (num_enemies);
	}

I’m expecting a num_enemies to be 3 since there are only 3 enemies at the current time, but it prints this:

79056-console.png

I need num_enemies to be equal to 3, so i can do other calculations with that variable.

Hi,

Your code appears accurate. I made a demo and used it and confirm its accurate.

If you are not getting as many instances as you expect, i have a few ideas

  • Did you properly tag all the GameObjects you want? (see image attached)
  • Are all those GameObjects in the scene at the moment your code above is run? Try pausing then manually inspect the hierarchy to be sure all GameObjects are properly tagged. (see code below)

Best Wishes!

-Sam

Code

     void Num_enemies()
         {
    
             EditorApplication.isPaused = true;
    
             GameObject[] getCount = GameObject.FindGameObjectsWithTag ("WeakSkeleton");
             int num_enemies = getCount.Length;
             Debug.Log (num_enemies);
         }