XDracam / unity-corelibrary

Collection of classes and extension methods that make life with Unity3D more comfortable
MIT License
15 stars 3 forks source link

transform.GetChildren fails when modifying children during iteration #8

Closed XDracam closed 5 years ago

XDracam commented 5 years ago

transform.GetChildren() is implemented using indices of the transform's children. The children are currently returned lazily using yield return. Bugs happen when children are added in-between or deleted while iterating the IEnumerable. This can be solved by manually calling .ToList() beforehand.

Potential solution

Make fetching of children eager. Returning a List directly would cause no code to break, as a List is an IEnumerable.

Might consider adding a GetChildrenLazy for edge cases with explicit ChildCount checking and error handling.

We cannot add the ChildCount checks into the default version, as adding and then removing a child before calling .MoveNext() again would still lead to weird bugs, so users should be beware of these issues.

XDracam commented 5 years ago

So, I actually wrote a test which does some random modifications during iteration and it worked when I used the builtin foreach (Transform t in transform). So I guess we can keep it that way.

TL:DR transform.GetChildren() now acts as lazy syntactic sugar for looping through the transform itself.