Count number of GameObject in the scene with specific tag in Unity

In game development with Unity using C# programming, you may have to count the number of objects with a specific tag. More practically, you need to get the updated statistic of the number of GameObjects with the same tag name.

Let’s first see how to count the number of Game Objects with a certain tag when the gameplay starts with the help of C# programming:

using UnityEngine;
public class GameObjectsByTag : MonoBehaviour
{
    void Start()
    { 
        GameObject[] objects = GameObject.FindGameObjectsWithTag("myTag");
        int count = objects.Length;
        Debug.Log("Found object with tag myTag is " +count);
    }

}

In the above example count the object with the tag myTag at the start. But, you may want to track it in the gameplay and need to get updated every moment. In that case, you have to put the code in the Update() method just as you can see in the example below:

using UnityEngine;
public class GameObjectsByTag : MonoBehaviour
{
    void Update()
    { 
        GameObject[] objects = GameObject.FindGameObjectsWithTag("myTag");
        int count = objects.Length;
        Debug.Log("Found object with tag myTag is " +count);
    }

}

In our example, we have first created an array of GameObject instances and store it in the variable objects. Here I am using the FindGameObjectsWithTag() method to get all the objects with a specific tag name that we provide as a parameter. After that, we get the number of that object as an integer by using the Length property and storing it in the count variable of the int type.

Finally, we are using Debug.Log to show the number of objects with the tag myTag.

Leave a Reply

Your email address will not be published. Required fields are marked *