I have a scene in which I destroy all the children of a parent gameobject and then use SetParent() method to bring different children back into that parent. The GetSiblingIndex() works fine the first time when the game runs. But once I destroy all the children and bring them back, unity just loses count. It keeps returning the sibling index of the last childobject that was destroyed. This is throwing ChildOutOfBounds!!..Please help!!
Destroy() delays destruction of the object until the end of frame. That’s why sibling indexes are not changed after calling this method.
I had posted this question quite some time ago… I figured out that the best way to remove all the children from a transform and update the child count right away, was to use the Transform.DetachChildren… This puts all the child gameobjects into the root of the hierarchy… To actually destroy them, before detaching them, you could tag all the child object with, say ‘ObjectToDestroy’ or whatever, and just collect all of them using GameObject.FindGameObjectsWithTag and destroy everything in the array one by one…Well this is if you want to destroy all the children… If you want to destroy selected ones, probably Symo7’s answer could come in handy - “using a List<> or Dictionary<> to store your list of objects to destroy”.
Anyways, thanks a lot for your suggestions…