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 /
  • Help Room /
avatar image
1
Question by RecChemForbin · Nov 20, 2011 at 10:12 AM · c#destroylistsforeachfor loop

Using foreach to remove and delete bullet in List - C#

Hi all,

EDIT: Using C#

I am trying to find a proper way to delete bullets and remove them from my List<>. Currently I'm removing them from within the foreach, and this gives me and exception becuase I'm trying to remove while the foreach is working:

 //Shooting
     if(Input.GetButtonDown("Fire1")){
         
         Rigidbody bulletClone;
         bulletClone = (Rigidbody)Instantiate(bullet, ship.transform.position + bulletCorrection, bullet.transform.rotation);
         bulletClone.velocity = transform.TransformDirection(Vector3.forward * bulletSpeed);
         bulletList.Add(bulletClone);
     }
     
     foreach(Rigidbody bulletSearch in bulletList){
         
         if(bulletSearch.rigidbody.position.x > 10){
             DestroyObject(bulletSearch.gameObject);                
             bulletList.Remove(bulletSearch);
             
             
         }
     }


I'm wanting to figure out the cheapest way to do something like this, and of course avoid errors.

I've tried using for loop, and creating seperate list to keep track of everything that needs destroying/removing but I've not been successful. If an answer is already available on this site or another please direct me there. Thanks--

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
0
Best Answer

Answer by aldonaletto · Nov 20, 2011 at 10:45 AM

Why do you need a list? If you just want to destroy the bullets which are above some y coordinate, forget about the list and place this code in the bullet script:

void FixedUpdate(){
    if (rigidbody.position.y > 10){
        Destroy(gameObject);
    }
}
But if you really need to keep all bullets in some list for other reasons, just let Unity do that for you: create an empty object, reset its position to 0,0,0, name it "Bullets" and child all bullet instantiated to it:

  Transform bullets; // <- drag the "Bullets" empty object here
  ...
    if(Input.GetButtonDown("Fire1")){
       Rigidbody bulletClone;
       bulletClone = (Rigidbody)Instantiate(bullet, ship.transform.position + bulletCorrection, bullet.transform.rotation);
       bulletClone.velocity = transform.TransformDirection(Vector3.forward * bulletSpeed);
       bulletClone.parent = bullets; // bullet is child of "Bullets"
    }
Every destroyed bullet is automatically removed from the children list, thus you don't need to update it yourself. If you need to iterate through all bullets, use a foreach like this:
       foreach (Transform bullet in bullets){
           // do whatever you want with this bullet
       }
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 RecChemForbin · Nov 20, 2011 at 12:29 PM 0
Share

Let me also note that this is in C# But what seems to be happening is that every time I fire the bullet, the reference to any transform is lost, so in order to retain this info to check for destruction parameters (past X location, and future collision detection) I'm storing in list, but will try doing your way and parenting with another object

avatar image RecChemForbin · Nov 20, 2011 at 12:46 PM 0
Share

alright, thank you sir! that worked great using the parenting

avatar image
0

Answer by Owen-Reynolds · Nov 21, 2011 at 12:49 AM

If you do want to use your own list, this works (I'm not a native C# programmer, so there may be a more standard way.) I used a LinkedList type just because. List is probably the same:

 LinkedList<MovingText> L; // global

 LinkedListNode<listType> nn = L.First;
 while(nn != null ) {
   // Play with nn.Value:
   nn.Value.update();
   // grab reference to next, so we can safely delete:
   LinkedListNode<listType> nNext = nn.Next;
   if(nn.Value.isDead()) { // isDead is just my hand-written check
     L.Remove(nn);
   }
   nn = nNext;
 }
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
avatar image
0

Answer by CaseyLee · Aug 18, 2017 at 09:35 AM

Old question, but no one seemed to notice the authors original code was getting an error because he was attempting to reference the object he had just destroyed...

  if(bulletSearch.rigidbody.position.x > 10){
      DestroyObject(bulletSearch.gameObject);      //. Destroying parent GO also destroys components.
      bulletList.Remove(bulletSearch);             //. Now he's trying to reference null obj.
  }
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 NoseKills · Aug 18, 2017 at 01:59 PM 0
Share

I don't think so. Destroy is not instantaneous so the object shouldn't be null yet. DestroyImmeadiate() might cause a problem.

The error is probably what the author says: modifying a collection you are enumerating over

avatar image Owen-Reynolds · Aug 18, 2017 at 02:44 PM 0
Share

The thing is, this is a typical total UA swerve question. The green answer really says "I think you're a total beginner in way over your head. You just grabbed that foreach off the internet and don't even know why you have a list. Just scrap it and use this limited, simple intro way ins$$anonymous$$d." And the OP accepted it, acknowledging "yes, you are correct."

So the poster asked a Q they didn't want the answer to, the first answer doesn't answer it, and, as N$$anonymous$$ points out, it's just a basic C# Q that doesn't belong here. I was a sucker and gave a straight answer (that was 6 years ago, but I still should have known better.) But now we have a HelpRoom, where "I'm lost and confused, any advice" Q's are fine.

Oh...I'm pretty sure I've used a Destroyed gameObject during that frame. I believe I've destroyed then disabled (in that order) and been fine. But it's probably a bad idea - the sort of thing that breaks in the next Unity version.

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

6 People are following this question.

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

Related Questions

simplest way to add a minimum distance or gap between instantiated objects 1 Answer

Compare GameObject with an array 1 Answer

Remove an object from a list and add another other obejct? 0 Answers

3 for loops and a IF crashes when the if is true 1 Answer

C# - Two lists linked with the same value 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