|
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: 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--
(comments are locked)
|
|
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: 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
Nov 20 '11 at 12:29 PM
RecChemForbin
alright, thank you sir! that worked great using the parenting
Nov 20 '11 at 12:46 PM
RecChemForbin
(comments are locked)
|
|
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:
(comments are locked)
|
