Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by pabloj100000 · Jun 19, 2015 at 06:39 PM · transformparentchildloop

Problem transferring children to a new parent

Hi

I'm trying to transfer all the children of an object to a new parent. The code below does not transfer all the items, it is skipping over some of them (explanation below)

     // Loop through all the children in old_parent and move them to new_parent
     foreach (Transform child in old_parent.transform) {
         Debug.Log("moving object: " + child.name);
         child.SetParent(new_parent.transform, false);
     }

However if I comment out the line changing the Parent, it does loop over every child

         // Loop through all the children in old_parent and move them to new_parent
         foreach (Transform child in old_parent.transform) {
             Debug.Log("moving object: " + child.name);
 //            child.SetParent(new_parent.transform, false);
         }

I do get the name of all the children.

I think this is the typical problem when you change the list (or array) you are iterating over. In pseudocode

 original list [A, B, C]
 the loop starts
   go fetch the element at position 0 (A)
   remove it, now list is [B, C]
 next iteration of the loop
   go fetch element at position 1 (and now this is C and not B)
   the list is [B]


I usually solve this problem iterating backwards from the end of the list but don't know how to do it in c# with game object.transform

Any ideas?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
6
Best Answer

Answer by zach-r-d · Jun 20, 2015 at 01:16 AM

Manual reverse iteration is possible using the GetChild() and childCount variables:

 for (int i=old_parent.childCount-1; i >= 0; --i) {
     Transform child = old_parent.GetChild(i);
     Debug.Log("moving object: " + child.name);
     child.SetParent(new_parent.transform, false);
 }

Additionally, this method performs no allocations, which is a nice bonus!

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bunny83 · Jun 20, 2015 at 02:01 AM 0
Share

btw: The Enumerator that Transform implements actually does the same thing but forward ^^.

avatar image zach-r-d · Jun 20, 2015 at 02:11 AM 0
Share

For sure! It's just that it allocates an instance of the Transform.Enumerator class in the process (wonder why it isn't a struct?).

avatar image Bunny83 · Jun 20, 2015 at 02:52 AM 1
Share

Well, mutable structs are actually something very evil ^^. .NET / $$anonymous$$ono implements most iterators for the generic classes as structs.

I found it quite suprising and interesting that the C# compiler doesn't actually use the IEnumerable interface when in comes to foreach loops. Just as fallback. That's the reason a struct enumerator actually works. If it would be based on the IEnumerable interface the actual struct would be boxed because interfaces are always reference types. The compiler actually does code analysis to deter$$anonymous$$e if a class actually implements the needed methods and calls those directly ins$$anonymous$$d of using an interface.

On the other hand Eric Lippert also suggest to not use mutable structs unless it's really necessary. See this and this as well.

avatar image zach-r-d · Jun 20, 2015 at 04:08 AM 0
Share

Ah, interesting! That explains how it's possible to have an enumerator for primitive types without boxing, in addition to how the enumerators themselves don't get boxed if they're value types. Good to know about the dangers of mutable types, too! That $$anonymous$$utating Readonly Structs post is crazy.

I'd completely forgotten about this until now, but sadly, the old version of $$anonymous$$ono that Unity uses under the hood will apparently box enumerator-structs in this case anyway. Even in 5.1.1f1, checking the mono version yields "2.0". Yeesh.

(For the record though, I support the use of foreach anyway because I$$anonymous$$O the paltry performance penalty doesn't offset the value of significantly cleaner code)

avatar image
2

Answer by JokerZappie · Mar 24, 2017 at 12:16 PM

A simple while loop like this does the trick too:

 Transform newParent = someTransform;
 Transform oldParent = someTransform;
 while (oldParent.childCount > 0) {
     oldParent.GetChild(oldParent.childCount - 1).SetParent(newParent, false);
 }

This iterates from the last/highest entry to the first/lowest entry.

Note that this puts all children in reversed hierarchy order into the new parent, so the first child becomes the last child.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Make a simple tree 1 Answer

Object scale/rotation changes when parented to flipped object 0 Answers

undoing parenting of object's transform 1 Answer

Separate child rotation 1 Answer

Assign parent object to target 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges