Search Unity

Destroying an instantiated object

Discussion in 'Getting Started' started by Altissimus, May 4, 2019.

  1. Altissimus

    Altissimus

    Joined:
    May 11, 2015
    Posts:
    49
    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!
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    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).
     
    Joe-Censored likes this.
  3. Altissimus

    Altissimus

    Joined:
    May 11, 2015
    Posts:
    49
    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?
     
  4. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    The script destroys itself. It looks something like this:
    Code (CSharp):
    1. void Update() {
    2.     if (transform.position.y < -10) Destroy(gameObject);
    3. }
    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.
     
    Jacoblo and Joe-Censored like this.