- Home /
Get child transform by index?
I'd like to access the child transforms of a game object by index (like an array). I know this is 'undefined', but as long as they don't randomly change order, I'm ok with it. Is there a clean way of doing this, short of using the 'foreach' clause and stopping it at the desired index?
Answer by Jessy · Jan 09, 2011 at 04:11 AM
Is this clean?
List<Transform> children;
void PopulateChildren () { children.Clear(); foreach (Transform child in transform) children.Add(child); }
(Withdrawing my untested, incorrect answer, replacing with this comment.) If Transform implemented IEnumerable like it ought to, then you could say children.AddRange(transform). I've put in a feature request for this ... http://feedback.unity3d.com/forums/15792-unity/suggestions/1361937-transform-should-implement-ienumerable-transform-
(Hmm, can I actually delete an answer, or just vote that it ought to be deleted ... ?)
It's deleted, but if you're signed in, you'll see your own deleted answers. I think you had good info about IEnumerable vs. IList, though, so I think maybe you should undelete it. I upvoted you for that, and for being a few seconds faster with a solution that should have worked. ;-)
heh, maybe I wouldn't be so quick with my answers if I actually tested them ... fair enough, I'll undelete and amend
If I add/delete children, I'd have to re-invoke this to repopulate that list, correct?