Search Unity

Question regarding deletion of objects

Discussion in 'Scripting' started by garrettskye, Mar 2, 2010.

  1. garrettskye

    garrettskye

    Joined:
    Jan 24, 2010
    Posts:
    5
    Hi, I'm relatively new to Unity, and have a quick question regarding some code of mine that isn't working quite like I would expect. I have an GameObject called Dude, that is destroyed upon the player colliding with it. That seems to work just fine. However, I have another game object called SpeechBubble that draws a GUITexture at the location of the Dude object. This also works. However, in the update of the SpeechBubble object I have the following code:

    Code (csharp):
    1.  
    2.     void Update()
    3.     {
    4.         if (target == null)
    5.         {
    6.             DestroyObject(gameObject);
    7.         }
    8.         else
    9.         {
    10.             thisTransform.position = Camera.main.WorldToViewportPoint(target.position + offset);
    11.         }
    12.        
    13.     }
    14.  
    Target is set to the Dude GameObject, and this almost works fine, except that the else code seems to run even after the Dude object is destroyed once. Also, the speech bubble is destroyed almost a second after the Dude is destroyed, and therefore null.

    I thought that objects were destroyed after all update calls. Sorry if this is really simple, but it's just kinda confusing me.
     
  2. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    Hi, welcome to the forum (and Go Packers!)

    I take it DestroyObject is your own function? You can just call Object.Destroy directly on the GameObject to remove it and this should indeed happen at the end of the frame.
     
  3. garrettskye

    garrettskye

    Joined:
    Jan 24, 2010
    Posts:
    5
    Thanks! With your help I actually discovered my problem. Since you confirmed I understood what should be happening, I started looking into other causes. Another script I had attached was turning off the renderer, and delaying the destruction for two seconds. I was just an idiot and kept forgetting to check that script for some reason. Got that fixed and everything works like a charm.