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 hawken · Sep 14, 2014 at 06:50 AM · javascriptlistnullremove

Remove Missing Objects from List

I have a list that is being monitored for it's length:

 var item_black : List.<GameObject>;

Some of the items placed in that list, sometimes get destroyed by the game, and I end up with a bunch of missing entries. One easy way I thought of clearing this is:

 function FixedUpdate () {
     for (var sweetie : GameObject in item_black) if (sweetie == null) item_black.Remove(sweetie);
 }

This actually works, but Unity throws an error:

 InvalidOperationException: Collection was modified; enumeration operation may not execute.
 System.Collections.Generic.List`1+Enumerator[UnityEngine.GameObject].VerifyState () (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:778)
 System.Collections.Generic.List`1+Enumerator[UnityEngine.GameObject].MoveNext () (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:784)
 item_toucher.FixedUpdate () (at Assets/my_script.js:55)

Whats the safest way of doing this? Do I need to remove the game objects explicitly back to this script as and when they are removed, or is there a way to do a RemoveAll(null list) or RemoveAt(null list) in UnityScript?

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

3 Replies

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

Answer by vexe · Sep 14, 2014 at 06:58 AM

You can't use a foreach loop to modify the contents of what you're enumerating (see this video for all the syntatic sugars behind foreach)

I would use LINQ for that:

 myList = myList.Where(item => item != null).ToList();

I think the syntax for JS is:

 myList = myList.Where(function(item) { return item != null }).ToList();

Another way to do it, is to iterate on your list backwards with a for loop, not foreach

 for(var i = list.Count - 1; i > -1; i--)
 {
    if (list[i] == null)
       list.RemoveAt(i);
 }


Comment
Add comment · Show 6 · 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 hawken · Sep 15, 2014 at 05:21 AM 0
Share

Hi thanks for the quick reply, great community this is.

The backwards counting for loop worked a treat, thanks a lot!

avatar image Shadoninja · Jun 23, 2018 at 06:02 PM 0
Share

Woah the backwards iterating trick is awesome. I have never thought of that.

avatar image mmalleske1 · Aug 30, 2018 at 03:59 AM 0
Share

Wow thanks! Worked perfectly for my situation where when the count hit a certain number it would fire an event.

avatar image Parzival · Apr 01, 2020 at 05:12 PM 0
Share

This worked for fixing my bug. Thank you kind sir.

avatar image myazuid · Feb 22, 2021 at 12:13 AM 0
Share

Hey @vexe , thanks for the solution here, very helpful! I know this is an old one, but figure I'll ask just in case. Would you $$anonymous$$d explaining why this needs to iterate backwards? What would be wrong with starting at index 0 and incrementing until you hit the list count -1?

avatar image SandLantern myazuid · Jul 19, 2021 at 07:56 PM 0
Share

@myazuid The reason is that when you remove an item from the list, you change the placement of every item after it. So if you're are iterating going from 0 => n-1, when you remove an item you now are in a different place in the list. Going from n-1 => 0 works because the list indexes are changing past where you are in the list.

avatar image
7

Answer by toomasio · Sep 16, 2016 at 10:54 AM

listItems.RemoveAll(item => item == null);

So if you have a GameObject list:

gos.RemoveAll(GameObject => GameObject == null);

Comment
Add comment · Show 2 · 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 Dorianosrex1 · Nov 11, 2018 at 09:17 PM 1
Share

That guy saved my life, thanks a lot!

avatar image eliteforcevn · Feb 26, 2021 at 06:36 PM 0
Share

Thanks you, you saved my life too

avatar image
1

Answer by eagleeyez · Jul 24, 2020 at 04:32 PM

WOW, iterate on your list backwards with a for loop, not foreach

That solved my very big headache. Thank you.

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

13 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

Related Questions

A node in a childnode? 1 Answer

Any way to enabled all GameObjects in an Array List? (UnityScript) 1 Answer

Add a enemy to list and check min distance 0 Answers

null reference exception problem with generic lists in unityscript (i think...) 1 Answer

how do I remove a class item from a list? 1 Answer


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