Search Unity

Weird behavior: clones not being destroyed according to their scripts

Discussion in 'Scripting' started by Vitor Ferreira, Jan 4, 2014.

  1. Vitor Ferreira

    Vitor Ferreira

    Joined:
    Jan 1, 2014
    Posts:
    5
    So, I'm getting this weird (at least for a beginner like me) behavior when instanciating and destroying shots on this shoot 'em up sketch I'm trying to develop.
    Every Shot prefab has an instance of ShotScript.
    I have this inside it's Start():

    Destroy(gameObject, 20);

    Sooo... I'm expecting that the gameObject which has this instance of script attached to it to be the one destroyed after 20 seconds, so that the shots are always destroyed from oldest to newest, as in a FIFO behavior. But that's not what's happening. Apparently,
    every clone is being destroyed, but randomly. Let's say I have shots 1, 2, and 3, 3 being the oldest. After 20 seconds 1 or 2 gets destroyed instead of 3. To exclude any possibility of memory leaking, I've commented the Destroy line and I've got some 200 shots instantiated, but none of them was destroyed (as one would expect). So, I've ruled this possibility out. Oh, and I should also mention that I had this same problem when trying to destroy via OnTriggerExit2D.
    What am I missing here?

    P.S: an image illustrating my problem (I didn't mention, but Player is the shooter, not someone being shot):
    http://s12.postimg.org/pxpc696il/weird.png
     
    Last edited: Jan 4, 2014
  2. softwizz

    softwizz

    Joined:
    Mar 12, 2011
    Posts:
    793
    Try putting it in Awake() instead of Start()
     
  3. MDragon

    MDragon

    Joined:
    Dec 26, 2013
    Posts:
    329
    Also, before you fall into the problem somewhere down the line where you get serious frame rate or similar issues, it may be far more efficient to simply have a few of the clones, activate them, move them or such, deactivate/reset, and repeat (such as rapid gunfire)
     
  4. Vitor Ferreira

    Vitor Ferreira

    Joined:
    Jan 1, 2014
    Posts:
    5
    Hey softwizz, thanks for the reply. I did put it in Awake() as you advised, and happened the same thing. I already expected it, honestly, since I was already having this problem when destroying via OnTriggerExit2D. It has nothing to do with Start() :/
    On a sidenote, I forgot to mention:
    This only happens when there are enemies on auto-fire inside the scene.
    I've deleted them and then put them again. I will now test and see if I get the same results

    EDIT: Thanks MDragon, I'll try to do this.

    FINAL EDIT:
    Problem solved. Accidentally put your Shot prefab at the same Layer as the Background and you'll get this strange behaviour. I'm an idiot.
     
    Last edited: Jan 5, 2014