Home > Enterprise >  Unity 2D: Counting Objects in Scene
Unity 2D: Counting Objects in Scene

Time:12-20

So. The game has objects. They spawn in different places and there are always different numbers of them. When the player touches this object, the object disappears, and this is recorded in the script (1 point is added to the special variable point). I need to somehow count the number of ALL of these objects in the scene (let's call this number x), and then compare this number with point. And if point is equal to the initial number of objects on the scene (x), then a certain event will occur. My problem is that I need to somehow count the number of spawned objects (x). Any ideas?

No ides. Just need help)

CodePudding user response:

Without knowing the structure of your "spawning" script, it's challenging to provide a solution. But as a general idea, you could either:

A. Keep a counter (e.g. numberOfExistentObjects) which increments per new GameObject and decrements when it's destroyed upon being touched by the player

  • Then, you could create a comparison along the lines of if(numberOfExistentObjects == point){...}

B. Reference your newly instantiated/spawned GameObject by keeping reference in a list (or array) such as List<GameObject> mySpawnedGameObjects = new() and append or remove its elements when creating or destroying respectively.

  • You could then get the number of elements in this collection using .Count and compare that against your point variable.

If for some reason you can't keep a reference, or need a different approach, you could get all GameObjects of a particular type by using FindObjectsOfType<T>, so if all "touchable" objects have a TouchableObject class (or interface) you could do:

FindObjectsOfType<TouchableObject>().Select(x => x.gameObject).ToArray();

CodePudding user response:

In such cases I prefer to have a dedicated component on my prefab which allows to simply count/iterate the instances directly:

public class Example : MonoBehaviour
{
    private static readonly HashSet<Example> _instances = new();

    public static IReadOnlyCollection<Example> Instances => _instances;

    private void Awake ()
    {
        _instances.Add(this);
    }

    private void OnDestroy ()
    {
        _instances.Remove();
    }
}

this way any other object can get the current alive instances via

var amount = Example.Instances.Count;

foreach(var instance in Example.Instances)
{
    ...
}
  • Related