Counting Objects

Hi,

Hoe can i count all of the objects an put their name in a list?

So thanks.

2 Answers

2

Or you could use the built-in methods for obtaining the gameobjects in scene

GameObject[] allGameobjects = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[]; Debug.Log(allGameObjects.Length);

Or use tags to get the objects you want

GameObject[] objectsWithTag = GameObject.FindObjectsWithTag("myTag") as GameObject[];
Debug.Log(objectsWithTag.Length);

One solution would be to create all objscts from the script, better solution would be to make one static class and call it Counter (.cs): (Don't attach this script to anything)

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public static class Counter
{
   public static List<GameObject> GameObjects;
}

and another MonoBehaviour class and call it Counted(.cs):

using UnityEngine;
using System.Collections;

public class Counted: MonoBehaviour 
{
    void Start()
    {
        Counter.GameObjects.Add(gameObject);
    }
}

Attach this class to any GameObject that you want to have in your list "GameObjects". You can get the number of GameObjects from any other class(script) like this:

Counter.GameObjects.Count;

You can access every single GameObject in the list like this: (If you need things like name, transform (postion/rotation)...)

foreach(GameObject Single in Counter.GameObjects)
{
   Debug.Log(Single.name);//this will print objects name
}

or simply like this:

for(int i= 0; i<Counter.GameObjects.Count; i++)
{
   Debug.Log(Counter.GameObjects*.name);//this will print objects name*
*}*
*```*
*<p>p.s.*
*I didn't test this code, there may be an error in coding</p>*