Home > OS >  How to reference spawned objects in a scene?
How to reference spawned objects in a scene?

Time:12-21

My game has objects which are spawned in different places, and there are always different amounts.

When the player touches this object, the object disappears, and 1 point is added to the variable point.

I need to count the number of ALL of these objects in the scene and then compare this number against point. And if point is equal to the initial number of objects on the scene, then a specific event will occur.

My problem is that I somehow need to count the number of spawned objects.

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