Destroying an instantiated object

Hi,

I’ve spawned a bunch of baddies using:

Vector2 randomSpawnPosition = new Vector2(Random.Range(-screenHalfSizeInWorldUnits.x, screenHalfSizeInWorldUnits.x),screenHalfSizeInWorldUnits.y+halfEnemyWidth);
GameObject newEnemy = (GameObject)Instantiate(enemyPrefab, randomSpawnPosition, Quaternion.identity);
newEnemy.transform.parent = transform;

…so that they fall through the screen. Now I want to destroy them when they are off-screen, so that I don’t end up with a memory leak and several thousand instantiated objects forever falling through my RAM.

I tried using a timer. Didn’t work. I tried using .y axis. I’m sure it works, I just don’t know how to do it.

if (newEnemy.screenHalfSizeInWorldUnits.y < -10 ) Destroy(newEnemy);

…seems really logical, but the “newEnemy” isn’t the one that’s fallen, it’s the next one created.

So.

How do I reference each individually instantiated object some time after they’ve been instantiated?

Thanks!

Your baddie prefab should have a script on it. That script destroys its own GameObject when the time is right (based on time since Start, or its own transform.position.y, or whatever).

1 Like

Could you help me out a bit more with a line or two of code please?

I kinda assumed what you said was the case, but for some reason it isn’t behaving as intended.

When I try to call time, or transform.position.y, it ignores me. Running a Print() command to check what it’s doing gives the default values of a new baddie prefab.

So, specifically, how does the script know which prefab to destroy? I do not want to destroy them all.

In my OP: I posted a line against transform.position.y and it doesn’t work. Why not?

The script destroys itself. It looks something like this:

void Update() {
    if (transform.position.y < -10) Destroy(gameObject);
}

The important thing is that you put this script on the prefab. There will then be a separate instance of it on every baddie you instantiate. And each one will destroy itself at the appropriate time.

2 Likes