- Home /
Trying to deleate bullets once they leave the screen
I am trying to remove the bullets once they are no longer in use, so to far away to be any use to save frame rate drop but i cant get them to delete.
This is the code i am using.
if (bullet.position.z < muzzle.position.z){
Destroy (bullet.gameObject);
}
but all that comes up is "The variable bullet of "Bullet" doesn't exist any more" and the bullets just keep going in the game.
Answer by aldonaletto · Dec 19, 2012 at 12:25 AM
This error occurs because you keep comparing bullet.position.z even after bullet has been destroyed. You could add a simple clause to it:
if (bullet && bullet.position.z < muzzle.position.z){
Destroy (bullet.gameObject);
}
When the bullet doesn't exist anymore, bullet returns false and the comparison is skipped.
Another possibility is to check renderer.isVisible:
if (bullet && !bullet.renderer.isVisible){
Destroy(bullet.gameObject);
}
isVisible actually returns true while the object is inside any camera frustum, thus it will be destroyed when going outside the screen. But usually it's easier to simply add a Destroy(bullet.gameObject, 5); instruction to the code that creates the bullet, so that the bullet will be destroyed after a short life of 5 seconds (if not destroyed before by a collision, of course).
Your answer
Follow this Question
Related Questions
Firing bullets deleats player not bullet 1 Answer
How to delete things with a timer 5 Answers
bullets don't go forward 1 Answer