P
P
PurgaBot2021-09-28 21:48:16
Unity
PurgaBot, 2021-09-28 21:48:16

How do I get all objects falling on the trigger zone?

I want to get an array and make objects not spawn when a certain number of hits in the zone

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2021-09-29
@PurgaBot

The object script must contain some kind of public variable in_zone, which is false by default. Also, the object must be recognized somehow, for example, by a tag, but you can come up with many other ways. For example, the script for an object is called object_script. Then in the zone script:

List<GameObject>  objects;
void OnTriggerEnter(Collider other)
{
    if(other.tag == "object") //Можно выбрать любой тэг
    {
        if(!other.GetComponent<object_skript>().in_zone) // проверка не в зоне ли уже объект
        {
            other.GetComponent<object_skript>().in_zone = true; // объект попал в зону
            objects.Add(new GameObject());
            objects[objects.Count - 1] = other.gameObject; // Добавление в лист нового компонента
        }
    }
}

Well, then there you can look at objects.Count and compare it with what you need. Also, if somewhere there is a removal of objects from the sheet, then positions with null will appear in the sheet, then adding to the sheet is better to write like this:
bool x = true;
for(int i = 0; i < objects.Count;)
{
   if(objects[i] == null)
   {
       x = false;
       objects[i] = other.gameObject;
       other.GetComponent<object_skript>().in_zone = true;
       break;
   }
   ++i;
}
if(x)
{
   other.GetComponent<object_skript>().in_zone = true;
   objects.Add(new GameObject());
   objects[objects.Count - 1] = other.gameObject;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question