x


Kill object after time

So, I have a projectile prefab that is shot both by the player and by the turrets of my game. When I instance the prefab in the two different scripts, I give them two different tags, "wormProjectile" and "enemyProjectile". Because I didn't want to projectile to live forever, I attached a script to the prefab meant to kill it after a certain amount of time. I wanted the projectiles fired by the turrets to live a different length of time than the ones fired by the player, so I tried using the following script:

var lifetimeP = 1.0;
var lifetimeE = 2.0;

function Awake ()
{
    if (gameObject.CompareTag ("wormProjectile"))
    {
       Destroy (gameObject, lifetimeP);
    }
    if (gameObject.CompareTag ("enemyProjectile"))
    {
       Destroy (gameObject, lifetimeE);
    }
}

But it never goes into the if statements. I am sure my mistake is something simple, but can anyone help me? Thank you! I really appreciate it.

more ▼

asked Oct 20 '11 at 07:51 PM

Tommas gravatar image

Tommas
1 3 3 3

well, your running this in Awake(). Awake gets called once, when the script is loaded (or "woken up" as i like to think of it). You need it to run every time a shot is fired (inside your shoot function?).

Oct 20 '11 at 08:00 PM timsk
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

I suspect Awake is called during Instantiate, and your problem seems to confirm that: since you set the tag after Instantiate, Awake only sees the original prefab tag.
A direct solution would be to change the routine from Awake to Start. A better solution, however, would be to fire the projectile and call Destroy in the same code - each shooting code would set the appropriate life time right after the projectile birth.
Your worm shooting script, for instance, would become something like this:

    ...
    bullet = Instantiate(prefab, ...);
    Destroy(bullet, 1); // if bullet isn't a GameObject, use bullet.gameObject
    bullet.tag = "wormProjectile";
    ...
more ▼

answered Oct 20 '11 at 08:30 PM

aldonaletto gravatar image

aldonaletto
41.5k 16 42 197

Thank you both! That worked great. I will get the hang of this eventually.

Oct 20 '11 at 09:03 PM Tommas
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

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

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x764
x9

asked: Oct 20 '11 at 07:51 PM

Seen: 2245 times

Last Updated: Oct 20 '11 at 09:03 PM