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
1
Question by sdgd · Dec 29, 2013 at 10:52 PM · c#foreachworkdoesnt

why does foreach work only 1/2 of a time?

ok I've finally found what's wrong.

and I don't get the behavior.

IF I do it this way:

 private void RemoveWallsF(){
     Debug.Log("Number Of Children: " + transform.childCount);
     foreach(Transform Child in transform){
         Debug.Log("Here");
     //    Destroy(Child.gameObject);
         StaticSpawner.DeactivateMeF(Child.gameObject);
     }
 }

I get:

 Number Of Children: 40
 Here // 20 counts in colapse

Reason is because I change the child's parent when I deactivate him.

if I do:

 private void RemoveWallsF(){
     Debug.Log("Number Of Children: " + transform.childCount);
     foreach(Transform Child in transform){
         Debug.Log("Here");
         Destroy(Child.gameObject);
     //    StaticSpawner.DeactivateMeF(Child.gameObject);
     }
 }

I get:

 Number Of Children: 40
 Here // 40 counts in colapse

but why does it go through all if it's destroyed it's kinda same as it would go to a different parent, ...

and so I did this:

 private void RemoveWallsF(){
     Debug.Log("Number Of Children: " + transform.childCount);
     Transform[] Children = transform.GetComponentsInChildren<Transform>();
     Debug.Log(Children.Length);
     for (int i=1; i<Children.Length; i++) {
         Debug.Log("Here");
         StaticSpawner.DeactivateMeF(Children[i].gameObject);
     }
 }

I get:

 Number Of Children: 40
 Here // 40 counts in colapse

I don't understand the foreach loop, ...

why only 1/2 of a time, ...

Comment
Add comment · Show 2
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 T27M · Dec 29, 2013 at 11:50 PM 0
Share

Are you creating these child objects dynamically?

avatar image sdgd · Jan 01, 2014 at 11:38 AM 0
Share

On creation of GO I put it to Parent GO let say Controller

I do it same on Activation of GO

BUT on deactivation of GO I change the GO's parent to the spawner's $$anonymous$$ion parent so the hiearchy is cleaner and that I don't do:

for all children (even in deactivated) deactivate again, ... as it happenes it will take it out 2 times than and there where it'll be put 1. time it will no longer be there as it'll think it was a deactivated GO, ...

my designed pooling is in my Questions and Answers somewhere if you are really interested in it, ...

but I ain't going to post it here, ...

2 Replies

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

Answer by Bunny83 · Dec 30, 2013 at 12:04 AM

Foreach always works on IEnumerable objects. The Transform class implements the IEnumerable interface and that's why you actually can iterate over the transform object. UT implemented the IEnumerator like this:

 // C# (copied from UnityEngine.dll)
 private sealed class Enumerator : IEnumerator
 {
     private Transform outer;
     private int currentIndex = -1;
     public object Current
     {
         get { return this.outer.GetChild(this.currentIndex); }
     }
     internal Enumerator(Transform outer)
     {
         this.outer = outer;
     }
     public bool MoveNext()
     {
         int childCount = this.outer.childCount;
         return ++this.currentIndex < childCount;
     }
     public void Reset()
     {
         this.currentIndex = -1;
     }
 }

So the foreach loop uses this Enumerator object to iterate through the childs of a Transform object. As you can see they didn't implement any check if the "collection" has changed in between. That's why you essentially skip every second child because you remove the first so the second become the first, the third become the second, ...

Since the Enumerator increments the index each iteration you actually access index 0, 2, 4, 6, 8, ...

Here's a visualization:

               C0 C1 C2 C3 C4  (childcount == 5)
 index(0)      |
 
               C1 C2 C3 C4     (childcount == 4)
 index(1)         |
 
               C1 C3 C4        (childcount == 3)
 index(2)            |
 
               finished


Destroying the childs usually has the same effect. Maybe they changed something in the newer version of Unity.

Usually Enumerators should throw an Exception when the collection is changed during iteration. The List<...> Enumerator does this. If you Add or Remove an object while iterating a List in a foreach loop it would throw an InvalidOperationException with the text "collection was modified".

To prevent such an Exception or the behaviour you've seen, create a "copy of the collection". The Linq namespace adds a "ToList" method ro all IEnumerable which will create a List which will contain the elements of the collection.

However Unity only implements the non-generic IEnumerable interface and not IEnumerable so it has to be casted first:

 foreach(var child in transform.Cast<Transform>().ToList())
 {
     //...
 }

This usually work in all cases. Don't forget to add

 using System.Linq;
Comment
Add comment · Show 1 · 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 sdgd · Dec 30, 2013 at 12:22 AM 0
Share

thanks for such wide explanation.

now I perfectly understand it.

avatar image
1

Answer by netlander · Dec 01, 2017 at 04:30 PM

When we have a case of a foreach loop removing items and changing the IEnumerable, thus messing with the data structure, an elegant solution would be to use a plain old for loop and start from the end of the IEnumerable and therefore acting on the element before removing it. Since we're removing items from the end of the data structure, its internal order is not disrupted mid flight.

For example:

 for (int i = Children.Length - 1; i >= 0; i--)
 {
     ///
 }
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

21 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

How to access the Boolean for one object? 1 Answer

Error assigning to a variable 0 Answers

Network functions doesn't work 0 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