- Home /
Destroy bullet after 'lifetime'. Need help please C#
Hi Guys :)
I'm putting together a platform shooter game and I'm having a little trouble getting my bullets to destroy themselves after a certain time. As it's a platform this is proving a serious problem, the bullets carry on down to the next enemy AI and kills it long before the player AI gets there.
I have the following code attached to the bullet prefab to destroy the bullet after a certain amount of seconds. But it's not working -
public float lifetime = 2.0f;
void Awake ()
{
Destroy(this, lifetime);
}
The bullet prefab is a cyclinder game object, capsule collider with a rigidbody. It has a movement script associated with it to make the projectile... well, project. If it is necessary to post this also please let me know.
I have tried adjusting the lifetime value to see if it makes any difference to no avail. I've never used this type of script before so I'm not sure if I'm using it correctly. Any suggestions greatly appreciated. Be gentle... I'm learning :) Thanks
Answer by Bunny83 · Jan 21, 2013 at 10:34 PM
"this" always refers to the class instance you're in, in other words your script component. When you use Destroy on "this" you will just destroy your script component. What you want it to destroy the whole gameobject your script is attached to:
Destroy(gameObject, lifetime);