A
A
Alexander Pianov2019-10-04 11:53:45
C++ / C#
Alexander Pianov, 2019-10-04 11:53:45

How to remove the void from the sheet, left after the destruction of the objects included in it?

There are objects in a sheet called Group.

public List<GameObject> Group = new List<GameObject>();

Accordingly, when one of the objects is destroyed:
Destroy(gameObject);
Missing appears in its place in the group, and non-critical errors appear in the console.
How can you remove destroyed objects from the Group so that the sheet becomes smaller?
For example, there are 2 objects. The first object is destroyed. The second object should take the place of the first one, and the sheet should decrease in size by one slot.
Tried RemoveAt and Remove:
controller.Group.Remove(gameObject);
Destroy(gameObject);

Where controller is a separate sheet script that is accessed by the object being destroyed.
But there is a critical error. Any ideas?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Gaydak, 2019-10-04
@pr9niks

Let's try to explain what's wrong.

foreach (GameObject tmp in Group)
{
}

this is where you start iterating over all the elements.
but then you CHANGE the NUMBER of items in the collection.
and now the enumerator passes through the indices, but they no longer match. (They are not updated after the start).
As a result, if we destroy (not delete) the object by reference, through Destroy(gameObject);
remains a list of references to null;
If we delete objects from the collection during a hike through the collection, we get an error with indexes.
how to solve.
or do it with for
for(int i =0; i <list.Count;i++)
{
Destroy(list[i]);
list.RemoveAt(i);
i--; // сместили индекс,если было удаление, так как размер коллекции уменьшился

another option is just after the loop with Destroy(gameObject);
clear the list list.Clear(); (If all at once are always deleted)
The main thing I hope is that the essence of the problem becomes clear.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question