[SOLVED] How do I clone an Entity without cloning its children?

I can clone and entity using:

var newClone= this.entity.clone();

…but I want to make sure that only the top level one gets cloned without its children.

How would I do that?

Cheers :slight_smile:

Oh wait… i can just go through and destroy all of its children after I’ve cloned it. (That sounds terrible)

 for ( i=0;i< my_tracked_clone.children.length;i++) 
    {
        my_tracked_clone.children[i].destroy();
    }

Hah, you’ve found it :innocent:

I don’t think there is any other way, at least without using private API, other than what you propose: clone and remove all children.

By the way, destroying children with a regular loop like that (zero to last index) will skip some entities, because each time you remove a children the iterator skips the next element.

You should do that in reverse:

for (let i=my_tracked_clone.children.length - 1; i >= 0; i--) {
   my_tracked_clone.children[i].destroy();
}

I don’t understand that at all :slight_smile:

It’s the same loop as yours, but instead of going from first to last child and removing it … it goes in reverse: last to first.

Ah, I suppose this is to avoid problems if there children nested within children?

Each time you destroy an entity, the .children array changes (it’s getting smaller), so the for/loop iterator if it had to iterate e.g. through 10 elements when it started … it now has fewer elements. So iterating from first to last will skip some elements.

If you do it in reverse, no issue.

1 Like

Okay Thanks. I suppose I could forward though if I did this though right…?

 this.my_children_length=my_tracked_clone.children.length;
    for(i=0;i<this.my_children_length;i++)
    {
        my_tracked_clone.children[i].destroy();
    }

No, better do it in reverse :innocent:

If you’d like to see why it will not work, try doing some console logs. You will see that each time you destroy an entity the indices are changing.

But surely if I assign a variable to be the length of the array once, it wont change as I iterate though a loop? The array length will change but my new variable is fixed/constant.
No?

Yes, but the length of the array isn’t constant, it changes each time you remove a child.

1 Like

Here is a similar issue:

1 Like

Got it. Thanks. That messed up my brain for the day. :slight_smile:

1 Like

Oh yeah, we all got messed up the first time we got to that :innocent:

1 Like