S
S
Sergey Serega2019-10-19 15:47:58
Unity
Sergey Serega, 2019-10-19 15:47:58

How to delete a number of child objects in unity?

It is necessary to remove a certain number of random child objects (For example, out of 500, 50 are left). I write like this:

int target = obj.transform.childCount - 50;
            int sum = 0;
            while (b)
            {
                Destroy(obj.transform.GetChild(
                    Random.Range(0, obj.transform.childCount - 1)
                    ).gameObject);

                sum++;

                if (sum == target)
                    break;
            }

Nothing is removed. I write like this:
int target = obj.transform.childCount-50;
            int sum = 0;
            while (b)
            {
                foreach (Transform t in obj.transform)
                {

                    if (Random.Range(0, 100) < 5)
                    {
                        Destroy(t.gameObject);
                        sum++;
                    }

                }

                if (sum == target)  
                    break;
                

            }

It just loops.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Gaydak, 2019-10-19
@SirSerega

you will probably have to lay out a mini project - which you can run.
so in appearance - the code is more or less adequate, except for the moment "what if target is negative ??"
here is less than 50 child)) - you will get an infinite loop.
the condition would do
while (target>0)
and in the loop after Destroy
target--;
the cycle would not start if there were not enough children, and in general it was all more transparent.
I would also suggest without randomness, just delete it in such a cycle to make sure it works)
and so the debugger is in your hands - and see what the variables are equal to and why nothing is deleted))
I would generally copy all childs into a separate list - and only then with manipulated them.
since the Destroy operation does not work immediately (if simplified, then the next couple of frames - when the engine is more comfortable)
, it is possible that
obj.transform.GetChild()
obj.transform.childCount calls
continue to issue references to already, as it were, "deleted" objects - and it turns out that he deleted 50 objects 300 times.
although then I think you'd notice.
in general, debugging and debugging will help you)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question