How to count gameobjects by Tag in unity3D with C# ?

I was simulating the Monte Carlo Method for my assignment on course Game Based Simulation using Unity 3D.  I want to count the instantiated game objects. Though there are other methods like OnTriggerEnter(Collider other). But this method did not worked pretty well. The next method I want to try is to count the game object by their tag name. The process of implementing the code is like below.

First define game object class in public are like this

 

using UnityEngine;
using System.Collections;
using System.IO;
public class countfox : MonoBehaviour {
public int count_fox;
//public int count_rabbit;
public int count_rabbitNEW;
StreamWriter sw;
GameObject [] rabbit;
GameObject [] fox;

void Start(){
sw = new StreamWriter(“count_fox.txt”);
}

void Update(){

rabbit = GameObject.FindGameObjectsWithTag(“rabbit”);
count_rabbitNEW = rabbit.Length;
sw.WriteLine(” ” + count_fox+” “+ count_rabbitNEW+” “+System.DateTime.Now, true);
sw.Flush();

fox = GameObject.FindGameObjectsWithTag(“fox”);
count_fox= fox.Length;
if (count_fox == 0) {
Debug.Break ();

// Application.Quit ();
}
}

}

One thought on “How to count gameobjects by Tag in unity3D with C# ?”

Leave a Reply

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